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