Laravel: Use DB Transactions

Learn Laravel database transaction tips including automatic rollback, deadlock handling, manual control, and best practices for data integrity.

February 5, 20261 min readssbhattarai

The transaction method from the DB facade executes database operations atomically. Any exception triggers an automatic rollback before propagating the error.
Different use cases and options:

1. Auto Transaction (Recommended)


use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');
    DB::delete('delete from posts');
});

Auto-rollback on exception, auto-commit on success.

2. With Eloquent Models


DB::transaction(function () {
    $user = User::create(['name' => 'John']);
    $user->profile()->create(['bio' => 'Developer']);
    $user->posts()->createMany([...]);
});

If any operation fails, everything rolls back.

3. Deadlock Retry


DB::transaction(function () {
    User::find(1)->update(['votes' => 1]);
    Post::where('user_id', 1)->delete();
}, attempts: 5);

Automatically retries up to 5 times on deadlock.

4. Return Values


$user = DB::transaction(function () {
    return User::create(['name' => 'John']);
});

// $user is now available

5. Manual Control


DB::beginTransaction();

try {
    User::create(['name' => 'John']);
    Post::create(['title' => 'Hello']);
    
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}

Use when you need custom logic between operations.


Pro Tip: Use DB::transaction() for 99% of cases. Use manual transactions only when you need custom logic between operations.