Hamed Kamrava Hamed Kamrava - 3 months ago 22
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()
    and
    DB::transaction()

  2. DB::commitTransction()
    and
    DB::commit()

  3. DB::rollbackTransction()
    and
    DB::rollback()



Any helps would be appreciated.

Answer

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:

DB::beginTransaction();

// execute function logic...

DB::commit();

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.