3

I need to use transactions on mongodb in laravel-5.8. I am using jenssegers-laravel-mongodb and use like below snippet in my code but it does not rollback when one of queries failed.

$session = MongoDB::startSession();
$session->startTransaction();
try {
    Player::document()->update($updates, ['session' => $session]);
    $session->commitTransaction();
    return true;
} catch (\Exception $e) {
    $session->abortTransaction();
    return false;
}

As I found out, this package does not support transactions. I desperately need to support transactions in my code. Could you advise me what to do?

Nice91
  • 91
  • 9

1 Answers1

0

Instead of using MongoDb class try using the Laravel's DB class, manually change the database driver your are connecting to and run the DB transactional commands as show below


\DB::connection(config('database.connections.mongodb'));
\DB::beginTransaction();

try {
    Player::document()->update($updates, ['session' => $session]);
    \DB::commit();
    return true;
} catch (\Exception $e) {
    \DB::rollback();
    return false;
}

MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
Starks
  • 37
  • 4
  • What about create() method of eloquent ? It does not take options so how do we pass session ? – Ravish Nov 10 '21 at 10:21