0
0
Laravelframework~5 mins

Queue workers in Laravel

Choose your learning style9 modes available
Introduction

Queue workers help your Laravel app do tasks in the background. This keeps your app fast and smooth for users.

Sending emails after a user signs up without making them wait
Processing uploaded images or files without slowing the page
Running reports or data imports that take time
Handling notifications or messages to users in the background
Syntax
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.

Examples
This starts a worker that listens to the default queue connection and processes jobs as they come.
Laravel
php artisan queue:work
This starts a worker that listens to the Redis connection and only processes jobs from the 'emails' queue.
Laravel
php artisan queue:work redis --queue=emails
This worker will try to run a job 3 times before marking it as failed.
Laravel
php artisan queue:work --tries=3
Sample Program

This 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.

Laravel
<?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
OutputSuccess
Important Notes

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.

Summary

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.