Labs ICT
Pro Login

Queues and Jobs

Handling background tasks.

Why Use Queues?

Queues let you defer time-consuming tasks like sending emails or processing uploads. Instead of making users wait, dispatch the work to the background and respond immediately.

Creating a Job

Use artisan to generate a job class. The command creates a clean, ready-to-customize class in the app/Jobs directory.


php artisan make:job SendWelcomeEmail
    

The job class has a handle method where you put the logic you want to run in the background.


class SendWelcomeEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public User $user)
    {
    }

    public function handle(): void
    {
        Mail::to($this->user->email)->send(new WelcomeMail);
    }
}
    

Dispatching Jobs

Fire off a job with the dispatch function. The job goes to the queue instead of running right away.


use App\Jobs\SendWelcomeEmail;

SendWelcomeEmail::dispatch($user);
    

You can delay a job or push it to a specific queue.


SendWelcomeEmail::dispatch($user)->delay(now()->addMinutes(5));

SendWelcomeEmail::dispatch($user)->onQueue('emails');
    
Try it Yourself →

Running the Queue Worker

Start a queue worker to process jobs. The worker listens to the queue and runs jobs as they come in.


php artisan queue:work
    

Use queue:listen to restart the worker when code changes. In production, use a process manager like Supervisor to keep the worker running.

Failed Jobs and Retries

If a job fails, Laravel stores it in the failed_jobs table. You can retry or delete failed jobs with artisan.


php artisan queue:retry all

php artisan queue:failed
    

Limit retries on a job to prevent infinite loops.


class SendWelcomeEmail implements ShouldQueue
{
    use RetryableTrait;

    public int $tries = 3;

    public function retryAfter(): int
    {
        return 60;
    }
}
    

Queues keep your application responsive and your users satisfied.