📌 Why Use Queues & Jobs?
In real-world applications, some tasks are time-consuming and should not block HTTP requests:
- Sending emails or notifications
- Generating reports
- Processing images or videos
- Importing/exporting data
Laravel queues allow these tasks to run in the background, improving performance and user experience.
⚙️ Step 1: Configure Queue Driver
Laravel supports multiple queue drivers:
database→ store jobs in DBredis→ fast in-memory storagesqs→ AWS SQS cloud queue
Set queue driver in .env:
QUEUE_CONNECTION=databaseRun migration for database queue:
php artisan queue:table
php artisan migrate- Creates
jobstable to store queued tasks
🔹 Step 2: Create a Job
Generate a job:
php artisan make:job SendEmailJobapp/Jobs/SendEmailJob.php:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mail;
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function handle()
{
Mail::raw('Welcome to Laravel Queues!', function ($message) {
$message->to($this->user->email)
->subject('Laravel Queues Example');
});
}
}- Implements
ShouldQueue→ queued job handle()→ task executed in the background
🔹 Step 3: Dispatch Job
From a controller:
use App\Jobs\SendEmailJob;
public function sendWelcomeEmail($user) {
SendEmailJob::dispatch($user);
return "Email job dispatched!";
}- Job is added to queue
- Does not block the user request
🔹 Step 4: Process the Queue
Run queue worker:
php artisan queue:work- Continuously processes jobs in the queue
- Stops only on manual termination or system restart
For supervisor in production:
supervisorctl start laravel-worker- Ensures queue worker runs continuously even if server restarts
🔹 Step 5: Delayed Jobs
Schedule a job to run later:
SendEmailJob::dispatch($user)->delay(now()->addMinutes(10));- Useful for reminders, notifications, or delayed tasks
🔹 Step 6: Failed Jobs Handling
Configure failed jobs in .env:
QUEUE_FAILED_DRIVER=databaseCreate table:
php artisan queue:failed-table
php artisan migrateCheck failed jobs:
php artisan queue:failedRetry failed jobs:
php artisan queue:retry all🔹 Step 7: Job Batching (Optional)
Laravel allows batching jobs:
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
$batch = Bus::batch([
new SendEmailJob($user1),
new SendEmailJob($user2)
])->dispatch();- Monitor progress and completion status
- Useful for bulk tasks like sending newsletter to multiple users
📌 Key Takeaways
This week you learned:
Why queues & jobs improve performance
How to configure queue drivers (database, redis, sqs)
How to create and dispatch jobs
How to process queues with queue:work
How to handle delayed and failed jobs
Optional: batch jobs for bulk processing