
What Are Laravel Queues?
Laravel Queues allow you to defer processing of time-consuming tasks. Instead of processing tasks immediately, you can push them to a queue to be processed in the background. This dramatically improves your application's performance and user experience.
Think of it like a restaurant kitchen: when you order food, you don't wait at the counter while it's being prepared. Instead, your order goes into a queue and you're notified when it's ready. Laravel queues work the same way!
Why Use Queues?
Queues are essential for modern web applications. Here's why you should use them:
- Faster Response Times - Users get immediate feedback while tasks run in background
- Better Performance - Your app handles more concurrent requests
- Reliable Processing - Tasks won't fail if your app crashes or restarts
- Scalability - You can process tasks on different servers
- User Experience - No waiting for slow operations like email sending or file processing
Setting Up Queue Drivers
Laravel supports multiple queue drivers. Let's set up the most common ones:
Database Queue:
// config/queue.php
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
],
Create the jobs table:
php artisan queue:table
php artisan migrate
Redis Queue:
// Install Redis first
composer require predis/predis
// config/queue.php
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
'block_for' => null,
],
Creating Your First Job
Let's create a simple job to send emails:
php artisan make:job SendWelcomeEmail
Now implement the job:
// app/Jobs/SendWelcomeEmail.php
namespace App\Jobs;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendWelcomeEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
protected $password;
public function __construct(User $user, string $password)
{
$this->user = $user;
$this->password = $password;
}
public function handle(): void
{
Mail::to($this->user->email)->send(new WelcomeEmail($this->user, $this->password));
Log::info('Welcome email sent to: ' . $this->user->email);
}
public function failed(\Throwable $exception): void
{
Log::error('Failed to send welcome email to ' . $this->user->email . ': ' . $exception->getMessage());
}
}
Dispatching Jobs
You can dispatch jobs from controllers, models, or anywhere else:
// In a controller
use App\Jobs\SendWelcomeEmail;
use App\Models\User;
class UserController extends Controller
{
public function store(Request $request)
{
$user = User::create($request->all());
SendWelcomeEmail::dispatch($user, $request->password);
return redirect()->back()->with('success', 'User created!');
}
}
// Dispatch with delay
SendWelcomeEmail::dispatch($user)->delay(now()->addMinutes(5));
// Dispatch to specific queue
SendWelcomeEmail::dispatch($user)->onQueue('emails');
Job Processing and Workers
Once jobs are in the queue, you need workers to process them:
// Start a queue worker
php artisan queue:work
// Process specific queue
php artisan queue:work --queue=emails,notifications
// Process in daemon mode (for production)
php artisan queue:work --daemon
// Stop the worker
php artisan queue:stop
// Restart the worker
php artisan queue:restart
Conclusion
Laravel queues are a powerful feature that can dramatically improve your application's performance and reliability. By moving time-consuming tasks to the background, you can provide better user experiences and build more robust applications.
Start with simple jobs like email sending, then gradually move to more complex scenarios. Remember to always test your queue jobs and implement proper error handling for production environments.
Happy coding with Laravel queues!