Laravel Transactions

A transaction start with the first executable SQL statement and ends when it is committed or rolled back.Query inside transaction are completely safe because you can choose to rollback all queries made within the transaction at any time.

DB::transaction() Method

Laravel provide DB::transaction() method to perform transaction.

DB::transaction(function()
{
    DB::table('employee')->where('salary', '>', 50000)->get()
    DB::table('user')->delete();
});

In above example we have run two query,they will all be committed or rolled back based on success or failure of any given query.

Running Transaction Manually

To perform transaction manually we use following function.

  1. DB::beginTransaction() :To begin a transaction.
  2. DB::rollback() :To rollback a transaction .
  3. DB::commit() :To commit a transaction.

Example

DB::beginTransaction();
try {
    DB::insert(...);
    DB::select(...);
    DB::commit();
    // all query executed
} catch (Exception $e) {
    DB::rollback();
    // something went wrong
}