Laravel queues implementation step by step

How many times you had some times consuming task to do with laravel in your application. Some times you need to send mail to a bunch of user but you can’t wait to do it in one request. Laravel have an awesome features named queue that let you delay time consuming operation. Queue can improve drastically your application. In this article we gonna implement laravel queue. Here is how to implement laravele queues step by step.

Requirements

To implement the queue you need a working installation of laravel or any other project with laravel 5.5 min. If you don’t have one you can follow the steps in my previous articles.

Database Setup

Laravel queue can be used with multiple drivers like beanstalk, redis, or simple database driver. For the sake of simplicity we gonna use the basic database drive.

To store our jobs we need a table in the database, laravel framework provide and easy way to do that. Just go to the terminal an execute the command below.

php artisan queue:table

The above command creates a migration file at database/migrations directory. The created file contains a schema similar to the content below for the jobs table.

<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
class CreateJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
}

Now time to migrate the table jobs to actually create it in your database. Run the following command to create it.

php artisan migrate

The database created we need to tell Laravel what driver we gonna use for the queue. For that just go to the .env and change the queue driver following the code below.

QUEUE_DRIVER=database

Create The job

I am writing this article using a real world example for a project. I actually need to download a playlist from youtube. What i am gonna do is create a job that will process each video. Let’s create the job by running this command.

php artisan make:job ProcessPlaylist

Once the above command executed, you will find  a job class is created at app/Jobs directory.

<?php
 
namespace App\Jobs;
 
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
 
class ProcessPlaylist implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
    }
}

We will update the code to run the exact piece of code to download each music from the playlist. I will not include the code to download the playlist here. If you are interested in it. Write it in the comment section and i will write an article about it.

<?php
 
namespace App\Jobs;
 
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
 
class ProcessPlaylist implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    $protected $url = "";
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($url)
    {
        $this->url = $url;
    }
 
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // here you put the code you want to execute with the url
    }
}

When you finish to setup your job in the queue go to your controller and call your job with your url inside it. Here is and example.

 public function downloadMusic($url) {
        $download = new ProcessPlaylist($url);
        $this->dispatch($download);
    }

Conclusion

To process the queue just go your terminal and execute php artisan queue:work and your queue will be executed. In a next article we will cover how to run the queue in background with multiple worker.

In this article we cover how to implement queue in Laravel step by step. If you have have problem with implementing it using our guide as usual drop in a comment in the section below. We will try to help you or just contact us in the messenger button we will answer as fast as possible. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *