laravel-mongodb: Database Transactions not working
Hello everyone, i stumbled on this issue today:
When i try to use laravel’s transactions like this
DB::transaction(function() use($data) {
$this->repository->create($data);
});
I get the following:
Call to a member function beginTransaction() on null
/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:108
/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:92
/vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:23
/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php:327
/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:221
I’m using laravel 5.4 and php version 7.1.
Is there any workaround for this issue?
This package is helping me out a lot with my personal project and i guess there is no other option for laravel and mongodb, so anything that solves it will do for me i guess.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 3
- Comments: 40 (3 by maintainers)
MongoDB 4.0 now supports multi-document transactions.
@jenssegers Any chance to have transactions working here? Let me know if you need help.
I got it working like this
As answered here
Any update on this @jenssegers ?
use
DB::connection('mongodb')->getMongoClient()
to access original MongoDB\Driver and useDB::connection('mongodb')->getMongoClient()->startSession()
to create a session and then start a transaction.@fidan-mkdir It seems to be included in the eloquent with jessengers and it seems to work properly with beginTransaction/commit/rollback I tested it with it and transaction seems to be working good.
This would be another excellent feature of the package!
PR with implementation https://github.com/jenssegers/laravel-mongodb/pull/1904
@leoku7020 you should do update on the mongo document object (not the model)
Mongodb not support transactions. It has another logic for this. Check https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/
Just a friendly reminder. If you have multiple database connection, make sure you define it first before you initialize transaction. File : config/database.php
Then, you can use @salalaslam’s answer
File : app/Controllers/YourController.php
Hello,
Let me guess, you’re using one server? MongoDB transactions does work only with replica sets and sharded clusters.
Thanks!