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.
Regarding the use of packages, it is necessary to replace Jenssegers/laravel-mongodb:
Laravel
//Jenssegers\Mongodb\MongodbServiceProvider::class,
Zs\Mongodb\MongodbServiceProvider::class
Lumen
//$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->register(Zs\Mongodb\MongodbServiceProvider::class);
$app->withEloquent();
Eloquent only expands on transaction-related content, so it directly replaces Jenssegers/laravel-mongodb
//use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Zs\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {}
//use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Zs\Mongodb\Eloquent\Model as Eloquent;
class MyModel extends Eloquent {
protected $connection = 'mongodb';
}
For more Eloquent documentation see (http://laravel.com/docs/eloquent)
DB::beginTransaction();
try {
User::insert($userData);
UserInfo::insert($userInfoData);
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}