SupportWriter space ↗
← Back to the journal
Laravel

Move Laravel Background Work into a Queue

Separate additional work from HTTP responses with jobs, workers, and dispatch after commit.

DAdministrator · 21 Sep 2026 · 2 min read

You are reading a translated version.

An HTTP request should not always wait for lengthy follow-up work. A queue hands work to a worker. This separation requires a non-sync queue connection and a running worker.

Generate LogArticleSummary using php artisan make:job LogArticleSummary. This exercise writes a summary to the log to make the flow observable. Real workloads might generate reports; this tiny logging example is intended to demonstrate the mechanism rather than justify a queue for performance.

Implementation example

namespace App\Jobs;

use App\Models\Post;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class LogArticleSummary implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    public function __construct(public int $postId) {}

    public function handle(): void
    {
        $post = Post::find($this->postId);
        if (! $post) {
            return;
        }
        Log::info('Article summary prepared', ['post_id' => $post->id]);
    }
}
// After saving $post inside your application:
\App\Jobs\LogArticleSummary::dispatch($post->id)->afterCommit();
# With a configured non-sync queue and its required tables/service:
php artisan queue:work --tries=3

Check the result

Stop the worker, dispatch one job, then start it and inspect the log. Use a development queue for the exercise. afterCommit() prevents dispatch before a saving transaction commits.

Jobs may be retried. Repeating this log entry is harmless, but emails, payments, and file generation need appropriate duplicate handling. In production, supervise workers with a process manager and run queue:restart after deployment so workers load new code.

Reference

Official documentation

← Explore more notes