A Blog Of Random Coding Techniques & Experiments Robert Askam

How to use Laravel Queues to speed up your site Post How to use Laravel Queues to speed up your site 1 year ago

This tutorial will show you how to use Queues in Laravel 5.5 For Email Verification's, this tutorial can be used for an introduction into queues and will help you in future requirements. Firstly if you need to set up Auth with the simple command

php artisan make:auth
and follow my previous tutorial for creating the email verification. You can find that here.

Creating Tables and Migrations for Queues

Using Artisan commands this is made very simple.
php artisan queue:table
php artisan queue:failed-table
php artisan migrate

Update the.env file

Your .env file shouldn't change much from the previous tutorial. If you haven't looked I'm using Gmail and here is what the .env file should look like. Notice the addition of QUEUE_DRIVER.
QUEUE_DRIVER=database
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=rbaskam@gmail.com
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=rbaskam@gmail.com
MAIL_FROM_NAME="Rob Askam"

Create the SendVerficationEmail Queue Job

Run the following Laravel Artisan command to make a new queue job
php artisan make:job SendVerificationEmail
Now make your way to the new folder created in App/Jobs you should see a new job called SendVerificationEmail. Open this file and move the the Mail Namespace and along with the ConfirmEmail we added to the RegisterController in the previous tutorial into the Job.
Change the following.
//Add the user variable above the __contruct
protected $user;
//Add and assign the variable in the constructor.
public function __construct($user)
{
$this->user = $user;
}
//Now in the handle method we need to send the email, cut this out of the protected function registered in the Register Controller in the previous tutorial and change user to use the new variable.
Mail::to($this->user->email)->send(new ConfirmEmail($this->user));

Register Controller

Add the name space to the top.
use App\Jobs\SendVerificationEmail;
Where you moved the email send function out of registered add this.
dispatch(new SendVerificationEmail($user));

Testing the Email Verification Process

At the command line, execute the following command to start listening for the queue.
php artisan queue:work

Completing the Email Verification

On you Linux server run
nohup php /home/forge/default/artisan queue:listen > /dev/null 2>&1 &