Laravel 11 for Beginners: Using Queues

Arlind Musliu Portrait
Arlind Musliu

January 18, 2024 · 3 min read · 35 views

Laravel Blogpost Image

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Improved App Performance with Queues

Your site's performance can be just as important as the quality of your content. Slow load times or a sluggish interface can quickly turn readers away. That's where Laravel's queue system comes into play, helping you defer the execution of time-consuming tasks such as sending emails or processing images.

What are Laravel Queues?

Laravel Queues provide a unified API for deferring tasks to a later time, allowing you to perform resource-intensive tasks in the background without affecting the user experience. By moving tasks such as email sending or feed processing to a queue, you can respond to user requests quickly, while the server works through the queued jobs at its own pace.

Setting Up a Queue

Laravel supports various queue backends like Redis, Amazon SQS, and database-driven queues. For beginners, the database queue driver is a good starting point as it doesn't require additional services.

To set up a database queue, first, create a migration for the jobs table:

php artisan queue:table
php artisan migrate

Next, update your .env file to use the database queue driver:

// Other options

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

// Other options

Creating Jobs

In Laravel, queued tasks are represented as "Jobs." You can generate a new job class using the command:

php artisan make:job SendNewPostNotification

This command will create a new job class in the app/Jobs directory. Within this class, you define the task you want to perform. Here's an example job that sends an email notification when a new post is published:

<?php

namespace App\Jobs;

use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;

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

    protected $post;

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

    public function handle()
    {
        $mailable = new Mailable(...); // Your mailable class with post details
        Mail::to('[email protected]')->send($mailable);
    }
}

We explain the email process in detail in another article.

Dispatching Jobs

Once you've created your job, dispatching it is simple. You can dispatch a job from anywhere in your application, such as from a controller method when a new blog post is created:

<?php

namespace App\Http\Controllers;

use App\Jobs\SendNewPostNotification;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
		// Other stuff

        // Store the blog post...
        $post = Post::create($request->all());

        // Dispatch the job to send the notification
        SendNewPostNotification::dispatch($post);

        // Other stuff
    }
}

Running the Queue Worker

To process the jobs in your queue, you need to run the queue worker. You can start the worker with the command:

php artisan queue:work

For production environments, you should configure a process monitor to ensure that the queue worker does not stop running.

Handling Failed Jobs

Sometimes jobs fail. Laravel provides a way to handle failed jobs by inserting them into a failed_jobs table. To create this table, run:

php artisan queue:failed-table
php artisan migrate

You can then define the maximum number of times a job should be attempted before being logged as failed:

php artisan queue:work --tries=3

Conclusion

Laravel Queues are a powerful feature that can significantly improve the responsiveness and efficiency of your application. By offloading time-consuming tasks to the background, you can ensure that your readers enjoy a fast and seamless experience on your site.

Upcoming Articles in the Series

  1. Laravel for Beginners: Sending Emails

  2. Laravel for Beginners: Localization and Languages

  3. Laravel for Beginners: Query Performance Issues and Debugbar


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!