As your Laravel application grows, so does the need to handle time-consuming tasks without slowing down your user experience. That’s where Laravel’s Job Queue system shines. In this post, I’ll guide you through why and how to use Laravel queues effectively, with real-life examples, commands, and best practices.
🧠 Why Use Laravel Job Queues?
Think of a job queue as a task line. Instead of doing everything instantly (and blocking the user), you offload tasks to a background process that handles it later.
Top benefits:
- ✅ Scalability: Offloads heavy logic like email or image processing.
- ✅ Concurrency: Multiple tasks can run in parallel using workers.
- ✅ Rate Limiting: Prevent overloading external APIs.
- ✅ Scheduling: Delay jobs to run at a specific time.
- ✅ Prioritization: Set queue priority to handle important tasks first.
🛠️ Typical Action Flow With Queues
Here’s a real-life pattern when handling requests:
Imagine you’re saving a form and sending a confirmation message afterward. You don't want users to wait for the message. Queue it!
🏗️ Creating a Simple Job
Use the Artisan command to create a job:
php artisan make:job SimpleMessageJob
Inside SimpleMessageJob.php
:
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class SimpleMessageJob implements ShouldQueue
{
use Queueable;
public function handle()
{
\Log::info("Simple log message from queue");
}
}
🚀 Dispatching Jobs
There are multiple ways to dispatch jobs:
Queue::push(new SimpleMessageJob);
dispatch(new SimpleMessageJob);
SimpleMessageJob::dispatch();
➕ Dispatch with Queue Name
You can assign a job to a specific queue:
SimpleMessageJob::dispatch()->onQueue('otp');
or inside the job constructor:
public function __construct()
{
$this->onQueue('otp');
}
🏃 Running the Queue Worker
To process jobs from a specific queue:
php artisan queue:work --queue=otp
To handle multiple queues with priority:
php artisan queue:work --queue=high,medium,low
Laravel will prioritize high
first, then medium
, and finally low
.
⏳ Delayed Jobs
Want to delay a notification by 10 seconds?
SimpleMessageJob::dispatch()->onQueue('otp')->delay(now()->addSeconds(10));
⚙️ Pro Tip: Organizing Job Queues by Action Type
Let’s say you're handling OTP verification and email sending. Use separate queues:
OtpVerificationJob::dispatch($user)->onQueue('otp');
SendEmailJob::dispatch($emailData)->onQueue('email');
Then run workers independently:
php artisan queue:work --queue=otp
php artisan queue:work --queue=email
Top comments (0)