How to set up a queue worker in Laravel?
Configure queue driver: Set QUEUE_CONNECTION to database or redis in the .env file; 2. Create task class: Use php artisan make:job to generate tasks that implement the ShouldQueue interface; 3. Set database tables: Run php artisan queue:table and migrate to create jobs tables; 4. Start queue worker: execute php artisan queue:work and add --tries, --delay and other parameters to control retry and delay; 5. Use Supervisor to keep running: Configure Supervisor to ensure that the worker continues to run and restart regularly to avoid memory leaks; 6. Distribute tasks from the code: push tasks through the Job::dispatch() or delay() method; 7. Monitor and retry failed tasks: Generate failed_jobs table, and use queue:failed, queue:retry and queue:flush to manage failed tasks; after completing the above steps, the Laravel queue system can handle tasks asynchronously.
Setting up a queue worker in Laravel is straightforward once you understand the basics of Laravel's queue system. Here's how to do it step by step.

✅ 1. Configure the Queue Driver
First, decide which queue driver you want to use. Laravel supports several: sync
(default, runs jobs immediately), database
, redis
, sqs
, etc.
Open your .env
file and change the QUEUE_CONNECTION
:

QUEUE_CONNECTION=database
Or for Redis:
QUEUE_CONNECTION=redis
? For local development,
database
is a good choice. For production,redis
orsqs
are more performant.
Then, make sure the corresponding config in config/queue.php
is set up correctly.
✅ 2. Create a Job (Optional but Common)
Generate a queued job using Artisan:
php artisan make:job ProcessPodcast
This creates a class in app/Jobs/ProcessPodcast.php
. You can dispatch it like:
ProcessPodcast::dispatch($podcast);
Make sure your job implements ShouldQueue
(the generated job does this by default).
✅ 3. Set Up the Queue Table (if using database driver)
If you're using the database
driver, create the jobs table:
php artisan queue:table
Run the migration:
php artisan migrate
This creates the
jobs
table where queued jobs are stored.
✅ 4. Start the Queue Worker
Run the queue worker with:
php artisan queue:work
This starts a worker that listens for new jobs and processes them.
Useful options:
-
--queue=high,low
– process specific queues -
--delay=5
– delay failed jobs by 5 seconds -
--tries=3
– retry failed jobs up to 3 times -
--timeout=60
– job timeout in seconds
Example:
php artisan queue:work --tries=3 --delay=2
✅ 5. Keep the Worker Running (Supervision)
The queue:work
command should run continuously in production. Use a process monitor like Supervisor .
Install Supervisor (Ubuntu/Debian):
sudo apt install supervisor
Create a Supervisor config:
/etc/supervisor/conf.d/laravel-worker.conf
[program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /var/www/your-app/artisan queue:work --sleep=3 --tries=3 --max-time=3600 autostart=true autorestart=true user=www-data redirect_stderr=true stdout_logfile=/var/www/your-app/storage/logs/worker.log stopwaitsecs=3600
⚠️ Note:
--max-time=3600
restarts the worker after 1 hour to avoid memory leaks.
Then reload Supervisor:
sudo supervisorctl read sudo supervisorctl update sudo supervisorctl start laravel-worker:*
✅ 6. Dispatch Jobs from Your Code
From a controller or service:
use App\Jobs\ProcessPodcast; ProcessPodcast::dispatch($podcast);
Or with delayed dispatch:
ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));
✅ 7. Monitor and Retry Failed Jobs
Laravel logs failed jobs in the failed_jobs
table. To create it:
php artisan queue:failed-table php artisan migrate
To log failed jobs:
php artisan queue:work --log-failed
View failed jobs:
php artisan queue:failed
Retry them:
php artisan queue:retry all
Or remove:
php artisan queue:flush
Summary
- Choose and configure a queue driver.
- Set up the database table if needed.
- Create jobs and dispatch them.
- Run
queue:work
and use Supervisor to keep it alive. - Handle failures and logging.
You're now processing jobs asynchronously. Basically, that's all it takes — not complex, but easy to miss a step.
The above is the detailed content of How to set up a queue worker in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

The most common way to generate a named route in Laravel is to use the route() helper function, which automatically matches the path based on the route name and handles parameter binding. 1. Pass the route name and parameters in the controller or view, such as route('user.profile',['id'=>1]); 2. When multiple parameters, you only need to pass the array, and the order does not affect the matching, such as route('user.post.show',['id'=>1,'postId'=>10]); 3. Links can be directly embedded in the Blade template, such as viewing information; 4. When optional parameters are not provided, they are not displayed, such as route('user.post',

The core of handling HTTP requests and responses in Laravel is to master the acquisition of request data, response return and file upload. 1. When receiving request data, you can inject the Request instance through type prompts and use input() or magic methods to obtain fields, and combine validate() or form request classes for verification; 2. Return response supports strings, views, JSON, responses with status codes and headers and redirect operations; 3. When processing file uploads, you need to use the file() method and store() to store files. Before uploading, you should verify the file type and size, and the storage path can be saved to the database.

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

There are two main methods for request verification in Laravel: controller verification and form request classes. 1. The validate() method in the controller is suitable for simple scenarios, directly passing in rules and automatically returning errors; 2. The FormRequest class is suitable for complex or reusable scenarios, creating classes through Artisan and defining rules in rules() to achieve code decoupling and reusing; 3. The error prompts can be customized through messages() to improve user experience; 4. Defining field alias through attributes() to make the error message more friendly; the two methods have their advantages and disadvantages, and the appropriate solution should be selected according to project needs.

Database Factory is a tool in Laravel for generating model fake data. It quickly creates the data required for testing or development by defining field rules. For example, after using phpartisanmake:factory to generate factory files, sets the generation logic of fields such as name and email in the definition() method, and creates records through User::factory()->create(); 1. Supports batch generation of data, such as User::factory(10)->create(); 2. Use make() to generate uninvented data arrays; 3. Allows temporary overwriting of field values; 4. Supports association relationships, such as automatic creation

TheTranslatorfacadeinLaravelisusedforlocalizationbyfetchingtranslatedstringsandswitchinglanguagesatruntime.Touseit,storetranslationstringsinlanguagefilesunderthelangdirectory(e.g.,en,es,fr),thenretrievethemviaLang::get()orthe__()helperfunction,suchas

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp
