Mastering Laravel 12 Queues: A Beginner’s Guide to Background Processing
Laravel Queues are like having a team of assistants who handle tedious work behind the scenes while your app stays fast and responsive. Whether it’s sending emails, processing images, or generating reports, queues ensure your users never wait. Let’s break down how to use Laravel 12 queues in simple terms, with practical examples anyone can follow!
🚀 Why Use Queues?
Imagine a pizza delivery app:
- Without queues: The cashier waits for the pizza to bake before taking the next order (slow!).
- With queues: The cashier takes orders instantly, and the kitchen handles pizzas in the background (fast and efficient!).
Queues help you:
✅ Speed up response times
✅ Handle failures gracefully (retry failed tasks)
✅ Prioritize important jobs (e.g., process payments before sending emails)
🔧 Setting Up Queues in Laravel
Step 1: Choose a Queue Driver
Laravel supports Redis, Amazon SQS, Beanstalkd, and databases. For simplicity, let’s use the database driver.
- Update
.env:
QUEUE_CONNECTION=database
- Create the jobs table:
php artisan queue:table
php artisan migrate
📝 Creating Your First Job
Jobs are tasks you want to run in the background. Let’s create a job to send a welcome email.
Step 1: Generate a Job
php artisan make:job SendWelcomeEmail
This creates app/Jobs/SendWelcomeEmail.php.
Step 2: Define the Job Logic
// app/Jobs/SendWelcomeEmail.php
public function handle()
{
$user = $this->user; // Passed via constructor
Mail::to($user->email)->send(new WelcomeEmail($user));
}
🔌 Dispatching Jobs
Send the job to the queue from anywhere in your code:
Example 1: From a Controller
use App\Jobs\SendWelcomeEmail;
public function register(User $user)
{
// Dispatch the job
SendWelcomeEmail::dispatch($user);
return "Check your email shortly!";
}
Example 2: Delay a Job
// Send email after 10 minutes
SendWelcomeEmail::dispatch($user)
->delay(now()->addMinutes(10));
👷♀️ Running Queue Workers
Workers process jobs in the queue. Start a worker:
php artisan queue:work
Pro Tips:
- Use
--queue=high,defaultto prioritize jobs (e.g.,highfirst). - Use
--tries=3to retry failed jobs 3 times.
💡 Real-World Examples
Example 1: Process Uploaded Images
// app/Jobs/ProcessImage.php
public function handle()
{
$image = Image::load($this->filePath);
$image->resize(800, 600)->save();
}
Dispatch:
ProcessImage::dispatch($filePath);
Example 2: Generate and Email Reports
// app/Jobs/GenerateReport.php
public function handle()
{
$report = PDF::generateReport($this->user);
Storage::put("reports/{$this->user->id}.pdf", $report);
Mail::to($this->user->email)->send(new ReportReady($report));
}
Dispatch with Priority:
GenerateReport::dispatch($user)->onQueue('reports');
Then run workers for the reports queue:
php artisan queue:work --queue=reports
🚨 Handling Failed Jobs
Sometimes jobs fail (e.g., API timeouts). Laravel makes retries easy.
- Set max tries in
.env:
QUEUE_TRIES=3
- Retry failed jobs manually:
php artisan queue:retry all
- Add cleanup logic to jobs:
// In your job class
public function failed(Exception $e)
{
Log::error("Job failed: " . $e->getMessage());
}
⏰ Scheduling Jobs
Run jobs automatically at specific times using the schedule method in app/Console/Kernel.php:
// Send weekly newsletters every Monday
protected function schedule(Schedule $schedule)
{
$schedule->job(new SendNewsletter)->weekly()->mondays();
}
Run the scheduler:
php artisan schedule:work
🌟 Best Practices
- Keep jobs small – Break large tasks into smaller jobs.
- Use Horizon – Monitor queues with Laravel Horizon (install via
composer require laravel/horizon). - Test with
syncdriver – SetQUEUE_CONNECTION=syncin.envduring testing.
🎯 Conclusion
Laravel Queues turn your app into a well-oiled machine:
- Faster responses – Users aren’t left waiting.
- Reliability – Retry failed tasks automatically.
- Scalability – Handle thousands of jobs effortlessly.
Start with simple jobs like sending emails, then explore advanced features like prioritized queues and scheduling. Before you know it, you’ll wonder how you ever built apps without queues!
Next Steps:
- Try Redis for faster queues.
- Explore Laravel Horizon for monitoring.
- Learn about job middleware for logging.
Now go offload those tasks and let Laravel Queues do the heavy lifting! 💪
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.