Use DB::afterCommit() to defer job dispatching until surrounding database transactions complete successfully.
Dispatching queue jobs inside active DB transactions can trigger race conditions where background workers run before the transaction commits. DB::afterCommit() delays side effects until commit finishes.
use Illuminate\Support\Facades\DB;
use App\Jobs\ProcessPayment;
DB::transaction(function () use ($order) {
$order->save();
// Guarantees worker receives committed database records
DB::afterCommit(fn () => ProcessPayment::dispatch($order));
});
- Prevents race conditions where queue workers query uncommitted database rows
- Discards callbacks automatically if transaction rolls back
- Can be set on jobs using public $afterCommit = true;
Related Tips
View all tips →Monitor Aggregate Queue Metrics with Total Size Helpers in Laravel 13.27
Laravel 13.27 adds totalPendingSize(), totalDelayedSize(), and totalReservedSize() to the Queue facade, making it easy to aggregate queue metrics for dashboards and health checks.
Debounce Queued Event Listeners with #[DebounceFor] in Laravel 13.26
Laravel 13.26 extends the #[DebounceFor] attribute to queued event listeners, collapsing bursts of repeated events into a single execution based on the latest resource state.