Create Queue Listener in Laravel 5

Laravel has an unified API for various queue back-ends. Queue allows us to process the time-consuming task faster, such as sending email which ultimately speed ups the web applications.

Steps to follow for creating Queue Listener:

  1. Install Supervisor

    Supervisor will automatically restart the queue if fails or stop working. To install Supervisor on Linux based system, use below command:

    sudo apt-get install supervisor

     

  2. Create ‘/etc/supervisor/conf.d/laravel-worker.conf‘ and paste the below code into it

    [program:laravel-worker]
    user=user_name
    process_name=%(program_name)s_%(process_num)02d
    command=php application_path/artisan queue:listen --sleep=3 --tries=3
    directory=application_path
    autostart=true
    autorestart=true
    numprocs=10
    redirect_stderr=true
    stdout_logfile=application_path/storage/logs/worker.log

    where,
    user_name: Your machine user
    application_path: Full path to your application

  3. Start the processes using following commands

    sudo supervisorctl reread
    sudo supervisorctl update
    sudo supervisorctl start laravel-worker:*

 

Now your queue listener is ready, let’s configure Laravel by following steps:


Step
1:

Set QUEUE_DRIVER=database in .env file

Step 2:
Navigate to queue.php file and check whether the table name and other settings for queue are present in database section

Step 3:
Run this command to migrate queue table in database

php artisan queue:table
php artisan queue:failed-table
php artisan migrate

 

You are ready for sending email through queue. Just replace Mail::send with Mail::queue or Mail::later

Final Steps:
Start and stop the following processes one by one to make Supervisor listen everytime (perform only if Supervisor doesn’t start listening automatically)

php artisan queue:listen
php artisan queue:work --daemon


*Note
:

1. Add ‘APP_URL‘ in .env file as per the accessible domain for application. If you’re using ‘url()‘ function in email which is queued, not adding ‘APP_URL‘ will generate a localhost URL.

2. While passing data to views when using Mail::queue or Mail::later the data isn’t accessible as expected. This happens when you’re passing an object or eloquent object and not as arrays. To make this work with queue you have to serialize the $eloquentObject first and later unserialize it in the view.

Mail::queue('emails.hello', serialize($data), function($message) {
...
});

Add this on top of view file:

{{-- */unserialize($data);/* --}}