Abel Lee
Abel Lee

Reputation: 55

Laravel 5.3 did not roll back if DB::transaction throws an error?

I tried to make a db transaction when I made multi queries.

and also I tried to catch the exceptions outside the transaction just like

DB::transaction(function() {
   try{
        //....db queries
   }catch(\Exception $e){
        Log::info($e);
   }
});

when some exceptions thrown here, the transaction seems like not be rolled back, the data has been changed in the database.

If I do DB::rollBack() in the catch statement manually, all my data will be fine,

it makes me think if I have to do DB::rollBack() manually?

but I do remember the doc of Laravel said if I am using DB::transaction to manage my db queries, when the exceptions threw, DB::rollBack() will be executed automatically?

It has been changed in Laravel 5.3?

Upvotes: 2

Views: 2288

Answers (4)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Follow this link. you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback()

Hope this work for you!

Upvotes: 4

Ohgodwhy
Ohgodwhy

Reputation: 50767

The proper way with transactions and try/catch is like this:

try {
    DB::transaction(function(){
        //your query stuff here
    });

    DB::commit(); //transactions had no error
} catch (\Exception $e ) {
    //transactions had an error
    DB::rollback();

    //do something with $e->getMessage();
}

The purpose is to give you greater control in the event that your queries fail. This way, you can catch the exception and roll the transaction back. Otherwise, you'd just perform the transaction.

Upvotes: 0

Rohit shah
Rohit shah

Reputation: 819

If You have multiple table entries and update depending on each Other .it is advised that you should use Transactions

$var_name = DB::transaction(function () {
//    DB operations.....
});

$var_name returns null when successful

for further details please refer to the doc https://laravel.com/docs/5.3/database

Hope this Helps you. Ask in case any query

Upvotes: 2

msonowal
msonowal

Reputation: 1687

it will not be executed automatically if you're implementing like that, but if you use it as a closure like below

DB::transaction(function () {
    //db queries
});

It will be rollbacked automatically.

Upvotes: 0

Related Questions