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, or any other drivers, as defined in the . you can use Redis 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 folder) and add two new columns in it. One for and second to check whether the user is . Following is the updated schema for the table: database/migrations email token verified user 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 and 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. MAIL_FROM_ADDRESS MAIL_FROM_NAME 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 along with the class file will be created inside the folder. This is the file I need to call when I need to send an email. Mail EmailVerification app Updating the EmailVerification Class This class comes with two methods. The first is the and the second is the 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 : constructor() build() $user protected $user; Now, add a new parameter in the constructor and pass this to the class variable . $user $user public function __construct($user) { //. $this->user = $user; } Next, update the method so that it can return a view along with the user token. build() 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 folder with name and then create a new file inside this folder with the name . This file will contain the following simple template: views email email.blade.php <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 appears inside the folder along with the job class. I will now edit this file so that it could be used to send email. Jobs app SendVerificationEmail First add Mail and EmailVerification namespaces in it. use Mail; use App\Mail\EmailVerification; Now create a new protected variable (also created in the EmailVerification class). Next, add a new parameter in the constructor() and pass its value to the class variable $user $user $user protected $user; public function __construct($user) { $this->user = $user; } Next, I will set up email sending process inside the method. handle() public function handle() { $email = new EmailVerification($this->user); Mail::to($this->user->email)->send($email); } What the function does is to create an instance of email verification template that is passed to Mail for sending off the email to a user. handle Update the Auth Registration Process Before getting started, add in array in the User Model. ‘email_token’ $fillable protected $fillable = [ ‘name’, ‘email’, ‘password’,’email_token’ ]; Now open file (located inside the folder). RegisterController.php Controller/Auth First add the following namespaces: use Illuminate\Auth\Events\Registered; use Illuminate\Http\Request; use App\Jobs\SendVerificationEmail; First modify the method and add the email_token in it. create() 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 encoding for the user’s email address. Next I added the following two new functions in it: base64 /** * 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 parent method and added two new lines in it. register() 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 method that will verify the user and its token. Next, I will create the views that I called in these two methods. verify() Create a new file in the folder with the name and paste the following code in it. views emailconfirm.blade.php @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 folder with the name Paste the following code in it. views verification.blade.php. @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 file for user verification: web.php 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 button, you will notice that the registration confirmation page opens up quickly because it is dispatched into the queue. Register 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 for it, which runs every minute. schedule a Cron job Conclusion In this article, I created email verification in the Laravel 5.4 using Queue and Mail. I have updated an existing 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. RegisterController
Share Your Thoughts