Laravel Queue: Step by Step Beginner Guide With Example

This article is a beginner-friendly, step-by-step guide to using Laravel queues. You’ll learn the core concepts, how to configure a queue driver, how to create and dispatch jobs, and how to run workers to process work off the main request cycle. Follow along with the example code and commands to get a functioning queued job running in a small Laravel app.

Introduction to Laravel Queues: Concepts & Setup

Laravel queues let you defer time-consuming tasks—such as sending emails, processing uploads, or generating PDFs—so they don’t slow down user requests. Instead of running these tasks synchronously during a request, you create “jobs” that are pushed to a queue and processed asynchronously by dedicated workers. Key benefits include faster HTTP responses, better UX, and more reliable background processing when load spikes.

Before writing jobs you need to choose and configure a queue driver. Laravel ships with several drivers: sync (runs jobs immediately), database, Redis, Beanstalkd, Amazon SQS, and more. For beginners the database driver is simple to start with because it only needs your app’s database. Set QUEUE_CONNECTION=database in your .env, then generate the jobs table with:

php artisan queue:table
php artisan migrate

For Redis-based queues (recommended for production) set QUEUE_CONNECTION=redis and ensure Redis is installed and configured in config/database.php and your .env.

Understand how workers operate: a worker process listens for jobs and executes their handle() method. You can start a worker locally with:

php artisan queue:work

or use queue:listen for automatic restarts on code changes (queue:work is preferred in production). For robust production operation, run workers under a process monitor (Supervisor, systemd) or use Laravel Horizon if you use Redis, which adds a nice UI and metrics. Also plan for failed-job handling by creating the failed jobs table with php artisan queue:failed-table and php artisan migrate.

Step-by-Step Example: Building Queues for Beginners

Let’s walk through a simple example: sending a welcome email after user registration without slowing the registration response. First generate a queued job:

php artisan make:job SendWelcomeEmail

Open app/Jobs/SendWelcomeEmail.php and ensure the class implements ShouldQueue and uses Queueable. Add a constructor to accept a User instance ID or array (avoid heavy Eloquent objects to prevent serialization issues), and write the email-sending logic in the handle() method. Example skeleton:

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;

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

    protected $userId;

    public function __construct($userId) { $this->userId = $userId; }

    public function handle()
    {
        $user = AppModelsUser::find($this->userId);
        Mail::to($user->email)->send(new AppMailWelcomeMail($user));
    }
}

Dispatch the job when a user registers. In your RegisterController or an event listener:

SendWelcomeEmail::dispatch($user->id)->delay(now()->addSeconds(10));

Or simply SendWelcomeEmail::dispatch($user->id); to run immediately via the queue.

Now run the worker to process jobs. Locally you can use:

php artisan queue:work --tries=3 --sleep=3

This command picks up queued jobs and retries failing ones up to the number of tries. For production, configure Supervisor with a minimal config (example) so workers restart automatically:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/artisan queue:work redis --sleep=3 --tries=3 --timeout=90
numprocs=3
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/laravel-worker.log

Also set up failed job storage:

php artisan queue:failed-table
php artisan migrate

Then inspect or retry failures with php artisan queue:failed and php artisan queue:retry {id}. For monitoring Redis queues consider installing Laravel Horizon for dashboards, metrics, and easy queue management.

Queues are a powerful tool to make Laravel applications responsive and scalable. Start with the database driver for learning, move to Redis and Horizon for production, and always run workers under a process monitor. Keep your jobs simple and serializable, handle failures gracefully, and test by dispatching jobs locally. For more details and advanced features (chaining, batching, rate limiting, middleware), consult the official Laravel docs—practice by converting one long-running task in your app into a queued job and you’ll quickly see the benefits.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments