Laravel 5.5 - Queue For Email Verification

in #utopian-io7 years ago (edited)

What Will I Learn?

  • To implement email verification after user registration
  • To use queue for email verification
  • To use Mailtrap.io for testing emails

Requirements

  • Laravel 5.5
  • Composer
  • XAMPP

Difficulty

Intermediate

Tutorial Contents

In this tutorial i will show, how you can use Queue in Laravel 5.5 for email verification by overriding default RigisterContoller. Queue can handle multiple requests ( for example sending emails ) to be processed in sequence and this make your app faster.

In this tutorial, I am going to use MySQL database for the queue jobs and Mailtrap.io for email testing. There are other ways how you can store queue jobs, as defined in the https://laravel.com/docs/5.4/queues.

Creating Laravel auth

php artisan make:auth

This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points. https://laravel.com/docs/5.5/authentication

Updating the Users Tables

First you have to update existing migration file for the users (folder: database/migrations) by adding two new columns in it, first email tokenand second for user verification status.

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();
});

Creating Table for Queue

Let’s create the table for queued jobs and failed job. For this propose, run the following commands:

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

Migrating the Tables

Now all the required tables are set up and you can run migration by following Artisan command:

php artisan migrate

migrated.jpg

Once Artisan command is finished, all the tables above will be generated.

Updating the .env File

Now we need to configure .env file with the mail and queue job driver.
As I mentioned in the beginning of this tutorial I will use Mailtrap.io to send verification emails. Maintrap.io was created to not spam emails in development phase of projects, once your app will hit the realease pahse you need to change this configuration.

QUEUE_DRIVER=database
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=mailtrap.io username
MAIL_PASSWORD= mailtrap.io password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS[email protected] 
MAIL_FROM_NAME=”My name”

Note: MAIL_FROM_ADRESS and MAIL_FROM_NAME are not by default in .env file, but I added this variables so I don’t need to specify the email address every time.

Creating Mail and the View for Email Verifications

At this point we are ready to create an email class which will return view and token to be sent with the email. To create an email setup run the following Artisan command:

php artisan make:mail EmailVerification

Once the command is completed, a new folder with the name Mail along with the EmailVerification class file will be created inside the app folder.

Updating the EmailVerification Class

This class comes with two functions constructor() andbuild(). In this class we are going to use $user entity to get email_token.

protected $user;

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

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.

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

Create the SendVerficationEmail Queue Job

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

php artisan make:job SendVerificationEmail

Once the comannd is completed, a new folder Jobs shows inside the app folder along with the SendVerificcationEmail job class. Now we are going to update this file.

protected $user;

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

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

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 we are going to update RegisterController.php file located inside the Controller/Authfolder. First add the following namespaces:

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

Modify the create() function 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’])
        ]);
}

Next override existingregister() parent method and add new verify($token) function.


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’);
}

public function verify($token)
{
        $user = User::where(‘email_token’,$token)->first();
        $user->verified = 1;
        if($user->save()){
        return view(‘emailconfirm’,[‘user’=>$user]);
}

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($token) method that will verify the user and its email_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 moment we are almost done and the last thing to do is add the following route in the web.php file for user verification:

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

Start listening for the queue

To start listening for the queue we need to run the following Artisan command:

php artisan queue:work

If you want to run queue jobs even after terminal is closed run the following command:

nohup php artisan queue:work &



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://hackernoon.com/how-to-use-queue-in-laravel-5-4-for-email-verification-3617527a7dbf

Your contribution cannot be approved because it does not follow the Utopian Rules, and is considered as plagiarism. Plagiarism is not allowed on Utopian, and posts that engage in plagiarism will be flagged and hidden forever.

Plagiarized from https://hackernoon.com/how-to-use-queue-in-laravel-5-4-for-email-verification-3617527a7dbf

You can contact us on Discord.
[utopian-moderator]

@shreyasgune thank you for your reply, but let me ask how many lines of text I can cite from some source, because I wanted to add bibliography section to let everybody know, that I was inspired by the other article.