Himanshu SharmaSoftware engineer
Let’s talk

Laravel · Lesson 31 of 40

Queues and jobs in Laravel

Move slow work out of the request with queued jobs, use the database queue, run a worker, set tries and backoff attributes, and inspect or flush failed jobs.

14 minBackground work and cachingUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite a queued job, dispatch it from a controller, run the worker, watch it in the jobs table, and handle a failed job.

What you can do after this lesson

You will move work that does not need to finish before the visitor gets an answer into the background. You will write a job, dispatch it, run a worker and see what happens when a job fails.

Why queues

Some work is slow (sending an email, resizing an image, calling another service) or may fail temporarily. If your controller does it inline, the visitor waits, and a failure becomes a failed page. A queue is a to-do list stored somewhere. The web request adds a job to it and returns right away. A separate worker process takes jobs off the list and runs them, retrying if they fail. The web app and the worker share code but run as different processes.

The default queue

In the fresh project, .env.example sets QUEUE_CONNECTION=database, and the third built-in migration created the jobs and failed_jobs tables you saw earlier. No extra software is needed. Real sites with heavy traffic often switch to Redis, but the code does not change, only the connection setting. In tests the queue is set to sync (look at phpunit.xml), which runs jobs immediately.

Writing a job

bash
php artisan make:job RecordReviewActivity
text
   INFO  Job [app/Jobs/RecordReviewActivity.php] created successfully.

Pagelane Books records an activity log line whenever a review is saved. It is small, but it shows the structure. Here is the finished class:

php
<?php

namespace App\Jobs;

use App\Models\Review;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Log;

#[Tries(3)]
#[Backoff(10)]
class RecordReviewActivity implements ShouldQueue
{
    use Queueable;

    public function __construct(public Review $review)
    {
    }

    public function handle(): void
    {
        Log::info('Review activity', [
            'review_id' => $this->review->id,
            'book_id' => $this->review->book_id,
            'user_id' => $this->review->user_id,
            'rating' => $this->review->rating,
        ]);
    }
}

implements ShouldQueue marks it as queueable. The Queueable trait (which in Laravel 13.42.0 brings Dispatchable, InteractsWithQueue, the bus queue options and SerializesModels) adds dispatch(). Because of SerializesModels, the job stores only the model's class and id in the queue and reloads the review fresh when it runs, so keep constructor data small: ids and models, not big arrays. #[Tries(3)] allows three attempts and #[Backoff(10)] waits 10 seconds between them; in older tutorials these are public $tries = 3; and public $backoff = 10; properties. Constructors that reload models pass the model itself, as here.

Dispatching

In both review controllers, after saving:

php
$review = $book->reviews()->updateOrCreate(['user_id' => $request->user()->id], $data);

RecordReviewActivity::dispatch($review);

The request now ends without writing to the log. To see the queue, post a review as a logged-in user, then look inside the database:

text
1 job(s) waiting
default attempts=0 App\Jobs\RecordReviewActivity

The log still had no Review activity entry at that point. Now run a worker. --stop-when-empty makes it quit when there is nothing left; in real use you let it run forever:

bash
php artisan queue:work --stop-when-empty
text
  2026-11-15 08:01:37 App\Jobs\RecordReviewActivity .................. RUNNING
  2026-11-15 08:01:37 App\Jobs\RecordReviewActivity ............. 14.37ms DONE
  2026-11-15 08:01:40 Worker STOPPED Queue empty

The log then contained local.INFO: Review activity {"review_id":8,"book_id":5,"user_id":2,"rating":5}, and the jobs table was empty again. Other options of queue:work include --once, --tries, --max-time and --queue for named queues, as queue:work --help lists. During development you can run php artisan queue:work in a second terminal. dispatchSync runs a job inline, which is useful for debugging.

When a job fails

A job that throws an exception is retried according to its tries. After the last attempt it is recorded in the failed_jobs table. A throwaway job whose handle threw RuntimeException('Demo failure') gave:

text
  2026-11-15 08:01:46 App\Jobs\FailingDemo ....................... 3.51ms FAIL
bash
php artisan queue:failed
php artisan queue:retry all
php artisan queue:flush

queue:failed lists failures with an id, connection, queue and class. queue:retry all (or an id) puts them back on the queue after you have fixed the bug. queue:flush deleted them in the demo, after which queue:failed reported No failed jobs found. Delete throwaway jobs like that one when you are done. Make jobs idempotent where you can, meaning that running one twice does no harm, because retries and crashes can run a job again.

Running workers in production

A worker boots the application once and keeps it in memory. After deploying new code, run php artisan queue:restart so workers exit and are restarted with fresh code; a process manager such as Supervisor or systemd keeps them running. Shared hosting without long processes may need a scheduled queue:work --stop-when-empty instead. The deployment lesson lists this in the checklist. Jobs that must run at set times use the scheduler, which Laravel also provides (php artisan schedule:list), though we do not build one here.

Common mistakes

  • Not running a worker, then wondering why nothing happens. Jobs wait in the table.
  • Forgetting to restart workers after a deploy.
  • Passing huge objects into the constructor. Pass ids or models.
  • Non-idempotent jobs that double-send or double-charge on retry.
  • Ignoring failed jobs. Monitor failed_jobs.

Exercise

Dispatch RecordReviewActivity with a 30-second delay, and say how the jobs row differs from an undelayed one.

Show one possible answer
php
RecordReviewActivity::dispatch($review)->delay(now()->addSeconds(30));

The row in jobs has an available_at timestamp 30 seconds in the future, so a worker skips it until then. Check with DB::table('jobs')->value('available_at') compared to now()->timestamp. Next: events and listeners, which decouple what happened from what should follow.

Key points

  • A queued job is a class that does work later in a separate worker process, so a web request can finish immediately.
  • A fresh Laravel 13 project uses the database queue; dispatching inserts a row into jobs and php artisan queue:work processes it.
  • Jobs implement ShouldQueue and use the Queueable trait, which also serialises Eloquent models by id.
  • In Laravel 13 the Tries and Backoff attributes set retries and delays; failed jobs land in failed_jobs and can be listed, retried or flushed.
  • A worker is a long-running process: restart it after deploying code, and run it under a process manager in production.

Check yourself

1. Why queue a job instead of doing the work inside the request?
2. Which command processes queued jobs?
3. What is stored in the jobs table row for a queued Review model?
4. You deploy new job code. Why restart queue workers?