Laravel Queues and Jobs

Lesson 38 of 50

76%
1. What Are Queues in Laravel?

Laravel Queues allow time-consuming tasks to run in the background instead of making users wait for the entire task to finish during a web request.

Examples of queue tasks:

  • Sending emails to students.
  • Generating PDF certificates.
  • Processing uploaded files.
  • Sending notifications.
  • Importing large amounts of data.

A job contains the task that should be performed. A queue worker retrieves queued jobs and executes them.

For example, when a student submits an admission form, Laravel can save the admission immediately and queue the welcome email for background processing.

2. Configure the Queue Connection

Laravel supports several queue backends, including database and Redis. For beginners, the database queue is a convenient option.

In your .env file, configure:

QUEUE_CONNECTION=database

Create the jobs table if your project does not already have the required migration.

php artisan make:queue-table
php artisan migrate

The exact migration command can vary by Laravel version. Check your project's existing migrations and Artisan commands before creating a duplicate table.

Important:

  • The database must be configured correctly.
  • The jobs table stores pending database-queue jobs.
  • A queue worker must run to process queued jobs.
3. Create Your First Job

Use Artisan to create a job class.

php artisan make:job SendWelcomeEmail

Laravel creates the file:

app/Jobs/SendWelcomeEmail.php

Example job code:

<?php

namespace App\Jobs;

use App\Mail\WelcomeMail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

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

    public function __construct(
        public string $email,
        public string $studentName
    ) {}

    public function handle(): void
    {
        Mail::to($this->email)->send(
            new WelcomeMail($this->studentName)
        );
    }
}

The ShouldQueue interface tells Laravel that the job should be processed by a queue worker.

This example assumes you already created the WelcomeMail Mailable and configured a working mail service.

4. Dispatch a Job

Dispatching a job places it on the configured queue for a worker to process.

For example, create a controller:

php artisan make:controller AdmissionController

Example controller method:

<?php

namespace App\Http\Controllers;

use App\Jobs\SendWelcomeEmail;
use Illuminate\Http\Request;

class AdmissionController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
        ]);

        // Save the admission record here.

        SendWelcomeEmail::dispatch(
            $validated['email'],
            $validated['name']
        );

        return response()->json([
            'message' => 'Admission received. Welcome email queued.',
        ], 202);
    }
}

The example assumes admission saving is implemented separately. In a real application, save the record successfully before dispatching the email job.

The HTTP status code 202 indicates that the request has been accepted for processing.

5. Run the Queue Worker

Laravel does not automatically process database-queue jobs just because they have been dispatched. Start a queue worker from your project directory.

php artisan queue:work

The worker retrieves pending jobs and executes their handle() methods.

Useful commands:

php artisan queue:work --once
php artisan queue:work --tries=3
php artisan queue:restart
  • --once processes one job and exits.
  • --tries=3 allows up to three attempts for a job, subject to job-level settings.
  • queue:restart asks running workers to restart gracefully after their current jobs.

Keep the worker running in a separate terminal during local development. Production workers should be managed by a process supervisor or an equivalent service.

6. Handle Failed Jobs

A job can fail because of a mail server problem, unavailable service, invalid data, or another exception. Laravel provides failed-job handling and retry controls.

Example configuration in a job:

public int $tries = 3;

public int $backoff = 10;

Add these properties inside the job class. This example allows up to three attempts and waits ten seconds before retrying after a failed attempt.

Inspect failed jobs:

php artisan queue:failed

Retry failed jobs:

php artisan queue:retry all

Forget a failed job:

php artisan queue:forget JOB_ID

The available failed-job commands depend on the queue configuration and Laravel version. Configure failed-job storage as required by your project.

7. Delay a Job and Choose a Queue

Laravel lets you delay a job or send it to a named queue.

Delay a job by five minutes:

SendWelcomeEmail::dispatch(
    'student@example.com',
    'Rahul Kumar'
)->delay(now()->addMinutes(5));

The job becomes eligible for processing after the delay. Actual execution also depends on the queue worker and queue backend.

Put a job on a specific queue:

SendWelcomeEmail::dispatch(
    'student@example.com',
    'Rahul Kumar'
)->onQueue('emails');

Process jobs from that queue:

php artisan queue:work --queue=emails,default

Laravel checks the queues in the order specified. Named queues help separate email tasks from other background work.

8. Queue Best Practices
  • Use queues for slow tasks that do not need to finish during the request.
  • Keep job data small and pass identifiers when appropriate.
  • Use retries and backoff for temporary failures.
  • Make jobs idempotent when possible so retries do not cause duplicate effects.
  • Monitor failed jobs and application logs.
  • Configure timeouts and retry limits appropriately.
  • Keep secrets out of job payloads and logs.
  • Use a process manager for production workers.

Important concept:

Queued jobs may execute more than once if a failure occurs at the wrong time. Design tasks such as payments and notifications carefully to prevent duplicate processing.

9. Practice Assignment

Build a simple email queue workflow.

  1. Configure Laravel to use the database queue.
  2. Create the required jobs table and run migrations.
  3. Create a SendWelcomeEmail job.
  4. Create a Mailable for the welcome email.
  5. Dispatch the job after a successful student registration.
  6. Start the queue worker and verify the email delivery.
  7. Configure retry attempts and a delay.
  8. Test how the application handles a failed job.

Bonus Task:

Create a separate certificates queue for generating student certificates and process it with a dedicated worker.

Quick Quiz

1. Which Artisan command creates a job class?




2. Which command starts a queue worker?




3. What is the main benefit of queues?