Why Queues?
Users hate waiting. Push slow tasks to background:
- Sending emails
- Processing uploads
- Generating reports
- Calling external APIs
Creating Jobs
php artisan make:job ProcessPodcast
class ProcessPodcast implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public Podcast $podcast
) {}
public function handle(): void
{
// Process the podcast
}
}
Dispatching Jobs
// Dispatch immediately to queue
ProcessPodcast::dispatch($podcast);
// Delay
ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));
// Specific queue
ProcessPodcast::dispatch($podcast)->onQueue('podcasts');
Running Workers
# Development
php artisan queue:work
# Production (with Supervisor)
php artisan queue:work --tries=3 --timeout=90
Handling Failures
class ProcessPodcast implements ShouldQueue
{
public $tries = 3;
public $backoff = [60, 120, 300]; // Retry delays
public function failed(Throwable $exception): void
{
// Notify admin, log error, etc.
}
}
Job Batches
Process many jobs as a group:
Bus::batch([
new ProcessFile($file1),
new ProcessFile($file2),
new ProcessFile($file3),
])->then(function (Batch $batch) {
// All jobs completed
})->catch(function (Batch $batch, Throwable $e) {
// First failure
})->dispatch();
Monitoring
# View failed jobs
php artisan queue:failed
# Retry failed
php artisan queue:retry all
# Clear failed
php artisan queue:flush
Use Laravel Horizon for Redis queues - real-time dashboard.
