SyntaxStudy
Sign Up
Laravel Introduction to Laravel Queues and Jobs
Laravel Beginner 1 min read

Introduction to Laravel Queues and Jobs

Laravel queues provide a unified API for deferring time-consuming tasks — sending emails, processing images, making third-party API calls — to background workers. Instead of slowing down an HTTP response, the task is pushed onto a queue and executed asynchronously by a queue worker process. Laravel supports several queue drivers: database, Redis, Amazon SQS, Beanstalkd, and the synchronous (sync) driver for testing. A job is a PHP class that implements the ShouldQueue interface and uses the Dispatchable, InteractsWithQueue, Queueable, and SerializesModels traits. The handle() method contains the job logic. Jobs are dispatched with the static dispatch() method or via the Bus facade. The data passed to the job constructor is serialized onto the queue and deserialized when the worker picks up the job. Laravel's queue workers are started with php artisan queue:work. The worker continuously polls the queue for jobs and processes them one by one. In production, Supervisor is typically used to keep the worker running and restart it if it crashes. The queue:listen command is similar but restarts the framework on each job, which is slower but useful for development when code changes frequently.
Example
<?php
// Generate a job: php artisan make:job ProcessPodcast

// app/Jobs/ProcessPodcast.php
namespace App\Jobs;

use App\Models\Podcast;
use App\Services\AudioProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 120;

    public function __construct(
        public readonly Podcast $podcast
    ) {}

    public function handle(AudioProcessor $processor): void
    {
        $processor->transcode($this->podcast->file_path);
        $this->podcast->update(['processed' => true]);
    }

    public function failed(\Throwable $e): void
    {
        // Notify developer or mark podcast as failed
        \Log::error('Podcast processing failed: ' . $e->getMessage());
    }
}

// Dispatch from a controller:
// ProcessPodcast::dispatch($podcast);
// ProcessPodcast::dispatch($podcast)->onQueue('audio')->delay(now()->addMinutes(5));