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

2

12

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.

Recension answered 27/8, 2016 at 6:59 Comment(2)
DB::commitTransaction() and DB::rollbackTransaction() do not exist.Unstrained
@Unstrained But I saw that here laracasts.com/discuss/channels/eloquent/…Recension
C
24

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

So this:

DB::transaction(function() {
    // Do something and save to the db...
});

is the same as this:

// Open a try/catch block
try {
    // Begin a transaction
    DB::beginTransaction();

    // Do something and save to the db...

    // Commit the transaction
    DB::commit();
} catch (\Exception $e) {
    // An error occured; cancel the transaction...
    DB::rollback();
    
    // and throw the error again.
    throw $e;
}

As you can see, DB::transaction() is a "helper" function to avoid writing code to catch errors, begin a transaction, commit the transaction, and optionally rollback (cancel the transaction) if an error occured.

If you have a more complex logic, or need an specific behaviour, you will manually build your transaction; if your logic is rather simple, DB::transaction() is the way to go.

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

It's a good practice to check the source code of the things you use, because you will learn how they are written, as well as how to write. Here's the file with the source for these methods.

Cambria answered 27/8, 2016 at 7:7 Comment(4)
Thank You. But I saw DB::commitTransaction0 here laracasts.com/discuss/channels/eloquent/…Recension
@Hamed Might have been a mistake.Unstrained
@HamedKamrava DB::commitTransaction() **Hesitancy
I think now DB::commitTransaction() has been renamed to DB::commit().Jaquesdalcroze
C
0

From Laravel 6 to use Transactions must be use the following helper functions.

use Illuminate\Support\Facades\DB;

try {
    // For Begin a transaction
    DB::beginTransaction();

    // Do something

    // Commit the transaction
    DB:: commit();
} catch (\Throwable $e) {
    // An error occured
    DB::rollback();
    
    // and throw the error again.
    throw $e;
}

if you use the DB::commitTransaction(); function, get error undefined function.

Collin answered 16/6, 2022 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.