Laravel Mongodb (Transactional support)
Introduction
Jensseger's laravel-mongodb extension package is very popular among Laravel developers, but it lacks a transactional feature. mongoDB 4.x supports multi-document transactions. Therefore, this package extends Jenssegers/laravel-mongodb with transactional support.
- mongoDB transactions are based on the mongoDB4.x replica set environment. mongoDB
- This package depends on Jenssegers/laravel-mongodb, so it needs to be installed first.
Installation
Regarding the use of packages, it is necessary to replace Jenssegers/laravel-mongodb:
Install by composer
composer require imanrjb/laravel-mongodb
Laravel
//Jenssegers\Mongodb\MongodbServiceProvider::class,
ImanRjb\Mongodb\MongodbServiceProvider::class
Lumen
//$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->register(ImanRjb\Mongodb\MongodbServiceProvider::class);
$app->withEloquent();
Eloquent
Eloquent only expands on transaction-related content, so it directly replaces Jenssegers/laravel-mongodb
use ImanRjb\Mongodb\Eloquent\Model;
class User extends Model {}
use ImanRjb\Mongodb\Eloquent\Model;
class MyModel extends Model {
protected $connection = 'mongodb';
}
For more Eloquent documentation see (http://laravel.com/docs/eloquent)
Usage
DB::connection('mongodb')->beginTransaction();
try {
User::insert($userData);
UserInfo::insert($userInfoData);
DB::connection('mongodb')->commit();
} catch (\Exception $e) {
DB::connection('mongodb')->rollBack();
throw $e;
}