A Beginner's Guide to Laravel Queues

Introduction

Laravel is a popular PHP framework that makes building web applications easier and faster. It provides a lot of features and tools to simplify the development process. One of these features is queues, which allow you to defer the processing of time-consuming tasks to improve the performance of your application. In this article, we will cover the basics of queues in Laravel and how to use them in your applications.

What are Queues?

A queue is a data structure that stores a list of tasks to be executed in order. In Laravel, a queue is used to handle tasks that can be processed in the background, without affecting the response time of your application. These tasks can be anything from sending emails to processing payments, and they are executed asynchronously by a separate worker process.

Queues help improve the performance of your application by allowing you to defer the processing of time-consuming tasks. This means that your application can respond faster to user requests, even if there are tasks that need to be executed in the background.

How do Queues work in Laravel?

In Laravel, queues are implemented using a combination of a queue driver and a worker process. The queue driver is responsible for managing the queue, while the worker process retrieves tasks from the queue and executes them.

Laravel provides several queue drivers out of the box, including Redis, Beanstalkd, Amazon SQS, and more. You can choose the queue driver that best suits your needs and configure it accordingly.

To add a task to the queue in Laravel, you can use the dispatch method. This method takes a job object as its argument, which is responsible for executing the task. For example, to send an email in the background, you can create a job object like this:

php artisan make:job SendEmailJob

This command will create a new job class in the app/Jobs directory. You can then define the logic of the job in the handle method of the class. For example, here's how you can send an email using the Mail facade:

public function handle()
{
    Mail::to('user@example.com')->send(new WelcomeEmail());
}

Once you've defined the job, you can dispatch it to the queue using the dispatch method:

SendEmailJob::dispatch();

This will add the job to the default queue, which is configured in the config/queue.php file. You can also specify a different queue by passing a second argument to the dispatch method:

SendEmailJob::dispatch()->onQueue('emails');

This will add the job to a queue called emails. You can then start the worker process to process the jobs in the queue:

php artisan queue:work

This command will start the worker process and begin processing jobs from the default queue. You can specify a different queue by passing a --queue option:

php artisan queue:work --queue=emails

This will start the worker process and begin processing jobs from the emails queue.

More Examples

Here are some more examples of how you can use queues in Laravel:

Processing Payments

If you're processing payments in your application, you can use queues to improve the performance of your checkout process. Instead of waiting for the payment to be processed before showing a confirmation page to the user, you can add the payment processing to a queue and redirect the user to a confirmation page immediately. The payment will be processed in the background, and the user can return to the site later to check the status.

<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessPayment implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $order;

    /**
     * Create a new job instance.
     *
     * @param  \App\Models\Order  $order
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Process the payment for the order
        $payment = $this->order->processPayment();

        // Update the order status to reflect the payment status
        if ($payment->isSuccessful()) {
            $this->order->markAsPaid();
        } else {
            $this->order->markAsFailed();
        }
    }
}

In this example, we're defining a ProcessPayment job that takes an Order object as its argument. The handle method of the job processes the payment for the order and updates the order status accordingly.

To add the payment processing to the queue, you can dispatch the job like this:

$order = Order::find(1);

ProcessPayment::dispatch($order);

This will add the ProcessPayment job to the default queue, which can be processed by a worker process using the php artisan queue:work command.

Found this helpful?

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe