Mastering Laravel 12 Queues: A Beginner’s Guide to Background Processing

Author

Kritim Yantra

Apr 29, 2025

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.

  1. Update .env:
QUEUE_CONNECTION=database
  1. 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,default to prioritize jobs (e.g., high first).
  • Use --tries=3 to 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.

  1. Set max tries in .env:
QUEUE_TRIES=3
  1. Retry failed jobs manually:
php artisan queue:retry all
  1. 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

  1. Keep jobs small – Break large tasks into smaller jobs.
  2. Use Horizon – Monitor queues with Laravel Horizon (install via composer require laravel/horizon).
  3. Test with sync driver – Set QUEUE_CONNECTION=sync in .env during 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:

  1. Try Redis for faster queues.
  2. Explore Laravel Horizon for monitoring.
  3. Learn about job middleware for logging.

Now go offload those tasks and let Laravel Queues do the heavy lifting! 💪

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts