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 →Automatically Discard Orphaned Queue Jobs with deleteWhenMissingModels
Use the $deleteWhenMissingModels property on queued jobs to silently discard jobs if their referenced database records were deleted before execution.
Prevent Queue Payload Bloat with withoutRelations()
Use withoutRelations() when passing models to queue jobs to prevent large in-memory relationship graphs from serializing into queue storage.