Queue workers help your Laravel app do tasks in the background. This keeps your app fast and smooth for users.
Queue workers in Laravel
php // Start a queue worker from the command line php artisan queue:work // You can specify the queue connection and queue name php artisan queue:work redis --queue=emails // To stop the worker gracefully, press Ctrl+C
Run queue workers in your terminal or server to process jobs.
You can run multiple workers for different queues or connections.
php artisan queue:work
php artisan queue:work redis --queue=emails
php artisan queue:work --tries=3This example shows a simple job class that sends a welcome email. The job is dispatched to the queue. When you run php artisan queue:work, the worker will process the job and print a message.
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class SendWelcomeEmail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public string $userEmail; public function __construct(string $userEmail) { $this->userEmail = $userEmail; } public function handle() { // Simulate sending email echo "Sending welcome email to {$this->userEmail}\n"; } } // Dispatch the job SendWelcomeEmail::dispatch('user@example.com'); // To run the worker, use the command line: // php artisan queue:work
Time complexity: Processing each job is usually O(1) but depends on the job's task.
Space complexity: Minimal for the worker itself; jobs may use more depending on data.
Common mistake: Forgetting to run the queue worker, so jobs stay pending.
Use queue workers when tasks take time and you want to keep the app responsive.
Queue workers run in the background to handle slow tasks.
Start workers with php artisan queue:work.
Dispatch jobs to queues to keep your app fast and smooth.