laravel eloquent transaction code example

Example 1: laravel db transaction

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

Example 2: DB::transaction

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');

    DB::delete('delete from posts');
});

Example 3: DB::transaction

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

Example 4: TRANSACTON LARAVEL QUERY BUILDER

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

Example 5: transaction laravel

DB::beginTransaction();
try { /** Statement */   DB::commit(); } 
catch (\Exception $e) { /** Statement if failed */ DB::rollback(); }

Tags:

Php Example