Creating and Running Redis Queue Jobs in Laravel 13
Laravel queues allow time-consuming tasks, such as uploading user avatars or calling external services, to run asynchronously.
When Redis is configured as the queue backend, jobs are stored in Redis and processed by queue workers.
1. Create a Job
Use Artisan to generate a job:
php artisan make:job UploadThirdAvatarToQiniu
In Docker, specify the Laravel project directory:
docker exec -it -w /var/www/html <php-container-name> php artisan make:job UploadThirdAvatarToQiniu
2. Define the Job
A job should implement ShouldQueue and use Laravel’s Queueable trait.
<?php
namespace App\Jobs;
use App\Services\UploadThirdAvatarToQiniu as UploadService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class UploadThirdAvatarToQiniu implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public int $timeout = 60;
public function __construct(
public int|string $userId,
public string $headImage,
public string $loginUpdateKey
) {}
public function handle(UploadService $uploadService): void
{
$uploadService->handle(
$this->userId,
$this->headImage,
$this->loginUpdateKey
);
}
}
Laravel’s service container can inject the service into the handle() method. You do not need to instantiate it manually.
3. Dispatch the Job to a Named Queue
You can keep the familiar dispatch() syntax and assign a custom queue name:
$job = (new UploadThirdAvatarToQiniu(
$userId,
$headImage,
$loginUpdateKey
))->onQueue('avatar-upload-to-qiniu');
dispatch($job);
This places the job in the avatar-upload-to-qiniu queue.
4. Run a Worker for the Correct Queue
A worker listening only to the default queue will not process jobs assigned to a different queue.
Start a worker with the required queue name:
php artisan queue:work redis \
--queue=avatar-upload-to-qiniu,default \
--tries=3
The queue names are checked in the order provided.
For Docker deployments, run the worker as a dedicated long-running service so it can restart automatically when the container is recreated.
5. Test a Single Job
During development, you can process one queued job and then exit:
php artisan queue:work redis \
--queue=avatar-upload-to-qiniu \
--once
This is useful when debugging jobs without keeping a worker running continuously.
Conclusion
Laravel 13 supports the standard job dispatching workflow, including dispatch() and onQueue().
Remember that dispatching a job and processing a job are separate operations: your Redis queue worker must listen to the queue where the job was placed.
