Lesson 38 of 50
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:
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.
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:
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.
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.
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.
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.
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.
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.
Build a simple email queue workflow.
SendWelcomeEmail job.Bonus Task:
Create a separate certificates queue
for generating student certificates and process it
with a dedicated worker.
1. Which Artisan command creates a job class?
2. Which command starts a queue worker?
3. What is the main benefit of queues?