Cloudways

@cloudways

How to Use Queue in Laravel 5.4 For Email Verification

Today, I will demonstrate how you can use Queue in Laravel 5.4 for email verification by using integrated auth RegisterController. In addition, I will also show you how to add the email sending process to a queue to make your app processes faster.

In this article, I am going to use a database for the queue jobs. However, you can use Redis or any other drivers, as defined in the official docs.

For the purpose of this article, I presuppose that you have created a Laravel auth using:

php artisan make:auth

If not, create it now. Once done, let’s get started with the tutorial.

Setting up the Tables

Let’s start with adding tables in a pre-existing database for the users and queues.

Updating the Users Table

Let’s first update the existing migration file for the user. Open the user table migration file (located in the database/migrations folder) and add two new columns in it. One for email token and second to check whether the user is verified. Following is the updated schema for the user table:

Schema::create(‘users’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->string(‘email’)->unique();
$table->string(‘password’);
$table->tinyInteger(‘verified’)->default(0);
$table->string(‘email_token’)->nullable();
$table->rememberToken();
$table->timestamps();
});

Adding Table for Queues

Let’s now add the table for queued jobs and failed job. For that, run the following Artisan commands:

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

Migrating the Tables

Now that I have all the required tables, let’s now migrate it using the following Artisan command:

php artisan migrate

Once the command is completed, all the tables will be generated.

Updating the .env File

I will now update the .env file with the mail and the queue driver information. I will use Gmail to send verification emails. Following are the changes in the .env file:

QUEUE_DRIVER=database
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=ahmedkhan27.92@gmail.com
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=ahmedkhan27.92@gmail.com
MAIL_FROM_NAME=”Ahmed Khan”

Notice that I have added two new constants MAIL_FROM_ADDRESS and MAIL_FROM_NAME so that I don’t need to specify the email address every time. As you could see, I have entered a Gmail address from which verification emails will be sent.

Creating Mail And the View For Email Verifications

Since I have setup SMTP to send emails, it’s time to create an email class which will return view and token to be sent with the email. Run the following Artisan command to create an email setup:

php artisan make:mail EmailVerification

Once the command finishes, a new folder with the name Mail along with the EmailVerification class file will be created inside the app folder. This is the file I need to call when I need to send an email.

Updating the EmailVerification Class

This class comes with two methods. The first is the constructor() and the second is the build() which will do most of the work. It binds the view with the email. I will send a user token along with the view so that the user can be verified. For this, add a new protected variable in the class with the name $user:

protected $user;

Now, add a new $user parameter in the constructor and pass this to the class variable $user .

public function __construct($user)
{
//.
$this->user = $user;
}

Next, update the build() method so that it can return a view along with the user token.

public function build()
{
return $this->view(‘email.email’)->with([
‘email_token’ => $this->user->email_token,
]);
}

Create the Email Template

For creating the email template, create a new folder inside views folder with name email and then create a new file inside this folder with the name email.blade.php. This file will contain the following simple template:

<h1>Click the Link To Verify Your Email</h1>
Click the following link to verify your email {{url(‘/verifyemail/’.$email_token)}}

The view for the email is now complete. Next, I will create a new queue that will send email(s) to the registered users.

Create the SendVerficationEmail Queue Job

Now run the following Artisan command to make a new queue job

php artisan make:job SendVerificationEmail

When the command finishes, a new folder with the name Jobs appears inside the app folder along with the SendVerificationEmail job class. I will now edit this file so that it could be used to send email.

First add Mail and EmailVerification namespaces in it.

use Mail;
use App\Mail\EmailVerification;

Now create a new protected variable $user (also created in the EmailVerification class). Next, add a new parameter $user in the constructor() and pass its value to the class $user variable

protected $user;
public function __construct($user)
{
$this->user = $user;
}

Next, I will set up email sending process inside the handle() method.

public function handle()
{
$email = new EmailVerification($this->user);
Mail::to($this->user->email)->send($email);
}

What the handle function does is to create an instance of email verification template that is passed to Mail for sending off the email to a user.

Update the Auth Registration Process

Before getting started, add ‘email_token’ in $fillable array in the User Model.

protected $fillable = [
‘name’, ‘email’, ‘password’,’email_token’
];

Now open RegisterController.php file (located inside the Controller/Auth folder).

First add the following namespaces:

use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use App\Jobs\SendVerificationEmail;

First modify the create() method and add the email_token in it.

protected function create(array $data)
{
return User::create([
‘name’ => $data[‘name’],
‘email’ => $data[‘email’],
‘password’ => bcrypt($data[‘password’]),
‘email_token’ => base64_encode($data[‘email’])
]);
}

For the email token, I have used the base64 encoding for the user’s email address. Next I added the following two new functions in it:

/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
dispatch(new SendVerificationEmail($user));
return view(‘verification’);
}
/**
* Handle a registration request for the application.
*
* @param $token
* @return \Illuminate\Http\Response
*/
public function verify($token)
{
$user = User::where(‘email_token’,$token)->first();
$user->verified = 1;
if($user->save()){
return view(‘emailconfirm’,[‘user’=>$user]);
}
}

What I have done is to override the register() parent method and added two new lines in it.

dispatch(new SendVerificationEmail($user));
return view(‘verification’);

This way the email is dispatched into the queue and instead of directly logging in that user, I will redirect him to another page which will ask him to verify his email in order to continue. Next I have created a new verify() method that will verify the user and its token. Next, I will create the views that I called in these two methods.

Create a new file in the views folder with the name emailconfirm.blade.php and paste the following code in it.

@extends(‘layouts.app’)
@section(‘content’)
<div class=”container”>
<div class=”row”>
<div class=”col-md-8 col-md-offset-2">
<div class=”panel panel-default”>
<div class=”panel-heading”>Registration Confirmed</div>
<div class=”panel-body”>
Your Email is successfully verified. Click here to <a href=”{{url(‘/login’)}}”>login</a>
</div>
</div>
</div>
</div>
</div>
@endsection

Create another new file in the views folder with the name verification.blade.php. Paste the following code in it.

@extends(‘layouts.app’)
@section(‘content’)
<div class=”container”>
<div class=”row”>
<div class=”col-md-8 col-md-offset-2">
<div class=”panel panel-default”>
<div class=”panel-heading”>Registration</div>
<div class=”panel-body”>
You have successfully registered. An email is sent to you for verification.
</div>
</div>
</div>
</div>
</div>
@endsection

At this point the code is complete and ready for use. Let’s give it a try.

Add the following route in the web.php file for user verification:

Route::get(‘/verifyemail/{token}’, ‘Auth\RegisterController@verify’);

Testing the Email Verification Process

At the command line, execute the following command to start listening for the queue.

php artisan queue:work

Leave the window of the command line open and open up the register page in another tab. Fill in the form and register a new user.

Once you click the Register button, you will notice that the registration confirmation page opens up quickly because it is dispatched into the queue.

Now look at command line: a new job has been processed successfully.

This means that an email has been sent to the user.

When the user click the link, he/she will be verified:

Note: Once you close the terminal, the queue will stop working. If you want the queue to continue listening, you can run the following command in your Linux terminal:

nohup php artisan queue:work &

The command will continue in the background, even if you close the terminal. Alternatively, you can schedule a Cron job for it, which runs every minute.

Conclusion

In this article, I created email verification in the Laravel 5.4 using Queue and Mail. I have updated an existing RegisterController which comes Laravel auth. I have also created a basic email template and verified the user through a code. Feel free to add you comments for further discussion.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

More by Cloudways

Topics of interest

More Related Stories