Run Code After Database Commit in Laravel Using afterCommit()

Avoid bugs by executing logic only after data is successfully saved.

  • 11 Apr, 2026
  • 20 Views

Run Code After Database Commit in Laravel Using afterCommit()

The Real Problem: Running Code Too Early

In real Laravel applications, you often do this:

DB::transaction(function () use ($data) {
    $order = Order::create($data);
    SendOrderEmail::dispatch($order);
});

Looks fine… but there’s a problem.

👉 The job may run before the transaction is committed.

This can cause:

  • Missing data
  • Inconsistent reads
  • Bugs in queues or events

The Solution: afterCommit()

Laravel allows you to run logic only after successful commit.

SendOrderEmail::dispatch($order)->afterCommit();

Real Project Example

DB::transaction(function () use ($data) {
    $order = Order::create($data);
    SendInvoiceJob::dispatch($order)->afterCommit();
});

Now:

  • Order is saved
  • Transaction completes
  • Then job runs safely

Share: