Some tasks are slow: sending email, resizing images, creating PDFs, calling other APIs. A queue runs them in the background so the user gets a fast response.
How it works
- Your code dispatches a job — it is saved to the queue
- A worker process (
php artisan queue:work) picks it up and runs it
Choose a queue driver
Set QUEUE_CONNECTION in .env:
sync— runs immediately (no background), useful for debuggingdatabase— stores jobs in thejobstable; simple and works on most hostingredis— faster, for busy sites
Create and dispatch a job
php artisan make:job SendWelcomeEmail— the class implementsShouldQueue, and the work goes inhandle()SendWelcomeEmail::dispatch($user);->delay(now()->addMinutes(10))— run later
Retries and failures
Set public $tries = 3; on the job. Jobs that still fail go to the failed_jobs table. php artisan queue:failed lists them and php artisan queue:retry all runs them again.
On the live server
The worker must keep running. Use Supervisor on a VPS. After deploying new code, run php artisan queue:restart so workers load it.
Example
<?php
// app/Jobs/SendWelcomeEmail.php
namespace App\Jobs;
use App\Mail\WelcomeMail;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
class SendWelcomeEmail implements ShouldQueue
{
use Queueable;
public $tries = 3;
public function __construct(public User $user) {}
public function handle(): void
{
Mail::to($this->user)->send(new WelcomeMail($this->user));
}
}
// After registration (controller):
SendWelcomeEmail::dispatch($user);
// Terminal: start a worker
// php artisan queue:work
Registration finishes instantly. The worker sends the email a moment later and retries up to 3 times if the mail server fails.