Laravel Queues Implementation Step by Step
Laravel Queues Implementation Step by Step
Learn how to implement and manage queues in Laravel for handling background jobs, improving application performance, and providing a better user experience.
Introduction
Laravel queues provide a way to handle time-consuming tasks in the background, such as sending emails, processing images, or generating reports. This guide will walk you through implementing queues in your Laravel application.
Prerequisites
- Laravel 6.x or higher
- Configured database
- Redis or database driver for queues
- Supervisor (for production)
1 Configure Queue Driver
Update your queue configuration in `.env`:
QUEUE_CONNECTION=database
QUEUE_DRIVER=database
Create the jobs table:
php artisan queue:table
php artisan migrate
2 Create a Job Class
Generate a new job class:
php artisan make:job ProcessOrder
Implement the job logic:
class ProcessOrder implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function handle()
{
// Process the order
$this->order->process();
}
public function failed(Throwable $exception)
{
// Handle job failure
Log::error('Order processing failed', [
'order_id' => $this->order->id,
'error' => $exception->getMessage()
]);
}
}
3 Dispatch Jobs
Dispatch jobs from your controller or service:
public function store(Request $request)
{
$order = Order::create($request->all());
ProcessOrder::dispatch($order);
return response()->json(['message' => 'Order queued for processing']);
}
4 Configure Queue Worker
Start the queue worker:
php artisan queue:work
For production, configure Supervisor:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=8
redirect_stderr=true
stdout_logfile=/path/to/worker.log
5 Monitor Queue Jobs
Monitor failed jobs:
php artisan queue:failed
Retry failed jobs:
php artisan queue:retry all
Key Features Covered
- Queue configuration and setup
- Job class creation and implementation
- Job dispatching and handling
- Queue worker configuration
- Failed job handling and monitoring
Best Practices
- Use job middleware for authentication and authorization
- Implement proper error handling and logging
- Set appropriate retry attempts and backoff
- Monitor queue performance and adjust workers
- Use job batching for related jobs
Common Issues
- Queue worker crashes and restarts
- Memory leaks in long-running jobs
- Failed job handling and retries
- Queue driver configuration issues
- Supervisor configuration problems