Hamed Kamrava Hamed Kamrava - 10 months ago 77
MySQL Question

What is the difference between DB::beginTransaction() and DB::transaction()?

I'm using Laravel 5.2.

I would like to know what are the differences between :

  1. DB::beginTransaction()

  2. DB::commitTransction()

  3. DB::rollbackTransction()

Any helps would be appreciated.


DB::beginTransaction() will only begin a transaction, while for DB::transaction() you must pass a Closure function that will be executed inside a transaction. Therefore:

DB::transaction(function() {
    // ....

is the same as doing:


// execute function logic...


And as you can see, DB::commit() will commit the current transaction.

It's worth noting that if any error occurs when you use DB::transaction(), Laravel will automatically catch them and run a rollback, because DB::rollback() will cancel the transaction (it's the opposite to DB::commit()). So we can say that DB::transaction() is nothing but a helper to avoid writing code to begin a transaction, catch errors, then rollback if an error occured or commit if everything was fine.

As for DB::commitTransaction() and DB::rollbackTransaction(), I can't find information.

It's a good practice to check the code directly, here's the file with the source for these methods.