Queues

Queues

Queue Configuration

Laravel supports multiple queue drivers:

  • sync: Runs jobs synchronously (default, useful for local development).
  • database: Stores jobs in a database table.
  • beanstalkd, SQS, Redis: More robust queue backends.

The default queue connection is set in .env via QUEUE_CONNECTION. For example:

PHP
QUEUE_CONNECTION=database

The database driver uses a jobs table to store queued jobs and a failed_jobs table for failed ones.

Dispatching Jobs to the Queue

In your JobController, change:

PHP
Mail::to($user)->send(new JobPosted($job));

to:

PHP
Mail::to($user)->queue(new JobPosted($job));

This queues the email instead of sending it immediately.

Running the Queue Worker

To process queued jobs, run:

Bash
php artisan queue:work

This command listens for jobs and processes them as they arrive.

Queued Closures

You can dispatch simple queued closures:

PHP
dispatch(function () {
    Log::info('Hello from the queue');
})->delay(now()->addSeconds(5));

This runs the closure after a delay, useful for deferred tasks.

Creating Dedicated Job Classes

Generate a job class:

Bash
php artisan make:job TranslateJob

Define the job’s logic in the handle() method. Dispatch it with:

PHP
TranslateJob::dispatch($jobListing);

IMPORTANT! Remember to restart your queue worker after code changes, because it saves it into its memory. Like php artisan tinker.

Tags: