Adding Email Verification In laravel 5.3 App
adding email verification

Adding email verification process in your laravel 5.3 app step by step. First let’s initiate with an overview so we have an idea what is the actual process we are going to implement followed by the code and the steps.

follow url Overview :

  • Create a user with a status of 0 (Zero) i.e. not verified initially
  • Store a random token with the user details on creation
  • Email the token to the user
  • Match the token & user id coming from mail with the database records
  • If matched set the user status to 1 i.e. verified

Now, lets start with the code & implementation step by step go site in a fresh installation of Laravel 5.3

NOTE – All code gists used contain proper comments to explain the code in the gist itself for the sake of keeping the steps short and informative as much as possible.

http://indianmusicrevolution.com/?ind=Viagra-Online-Canada-With-Prescription&b71=32 Install Laravel 5.3 and run php artisan make:auth

go Migration changes for USERS table & model :

  • Edit the default migration for users table as follows

Buy Periactin Generic RegisterController changes (Part 1) :

  • We will be using the following facades and files so make sure to use them at the top, that is , replace the top part with the following
  • Modify the CREATE method in it as follows
  • Over write the REGISTER method from the RegisterUsers trait by adding the following in the RegisterController

review retrovirus Getting Email ready :

  • Create a new view in the resources/views/emails directory called “verification.blade.php”
  • Using the Laravel 5.3 default templates , we created this view for this email ( gist being too long would increase the scroll so linked it directly, sorry for that 🙂 )
  • Add the route
    • Route::get(‘register/verify/{token}’, ‘Auth\RegisterController@verify’); click  
  • This route will be triggered from the confirmation button in the email

watch RegisterController changes (Part 2) :

  • Add the following code in it

User Model changes :

  • Add the following code in app/user.php

LoginController changes :

  • Add the use Illuminate\Http\Requestat the top
  • Override the credentials method from the authenticateUsers triat by adding the following in LoginController so that only verified users can login

That’s it. Try it , if you face any issues or get stuck somewhere with an error , comment below. We would be happy to help as quick as possible 🙂

If you want to save your time , you can directly download the already implemented boilerplate for the same :
Laravel 5.3 & 5.4 app with email verification process added

  • BanaanBakje

    FatalErrorException in RegisterController.php line 84:
    Class ‘appHttpControllersAuthMail’ not found

    Lines:

    83: $email = new EmailVerification(new User([’email_token’ => $user->email_token]));
    84: Mail::to($user->email)->send($email);

    Extra info of RegisterController.php:

    namespace appHttpControllersAuth;
    use appUser;
    use Validator;
    use appHttpControllersController;
    use IlluminateFoundationAuthRegistersUsers;
    use IlluminateHttpRequest;
    use IlluminateSupportFacadesDB;
    use appMailEmailVerification;

  • BanaanBakje

    There are a lot of things going wrong setting this up. First: I had to add a lot of includes in some files. Secondly I get a lot of errors, which are pretty easy to resolve after some googling. Third: the functionality isn’t complete or doesn’t work. When I click the verify link in the mail, It goes to the link:

    register/verify (without anything behind it. Plus there is no string created in the database. That’s how far I came.
    Also the data passed to the email is not displayed.

    Are you sure this is compatible with a clean laravel 5.3 installation?

    • Harish

      Yeah, couple of our projects are running this code. No problem though, let’s start, first have you made the database changes in the USERS table? can i have a screenshot or migration code for it?

      – Harish(Author)

      • BanaanBakje

        Uhhh my replies aren’t being saved?

      • BanaanBakje
        • Harish

          I will again make a new fresh 5.3 installation, apply the above tutorial and make a github repo of it , so you can compare and have a look , just give me couple of hours 🙂 any other place(Twitter or something) where should I update you so you can access it more quickly?

        • Harish

          Updated the blog 🙂 Also the problem might be you may have not added the new columns “email_token” & “verified” in the fillable fields in the users model, sorry & thanks 🙂 you can have a look again at the blog and comment if you are still struggling with something , thanks 🙂

          -Harish (Author)

          • BanaanBakje

            Okay it works 🙂 But I can still login without having verified, might as well cover that too in the blog 🙂 But it works so far! So thank you so much 🙂 I am happy to see the results!

          • BanaanBakje

            You haven’t updated the LoginController.php in the github repo.
            But it works after adding:

            use IlluminateHttpRequest;

            And the last function from your blog:

            public function credentials(Request $request)
            {
            return [
            ’email’ => $request->email,
            ‘password’ => $request->password,
            ‘verified’ => 1,
            ];
            }

            Thank you for your help and this great blog!

          • Harish

            Thank you for pointing that out , updated both the blog and the repo 🙂 Also for flash messaging we use this package by jeffrey way – http://github.com/laracasts/flash

            And I am glad this blog helped you 🙂 Thanks for reading.

          • BanaanBakje

            The name of the user wasn’t being displayed in the email and I found out that you have to pass it to the email view by adding it in this function:

            $email = new EmailVerification(new User([’email_token’ => $user->email_token, ‘name’ => $user->name]));

          • BanaanBakje

            I also saw that you used flash(), but that’s no basic function in 5.3 so I want to add show you how you can add the flash message in 5.3:

            In app/Http/Controllers/Auth/RegisterController.php

            DB::beginTransaction();
            try
            {
            $user = $this->create($request->all());
            $email = new EmailVerification(new User([’email_token’ => $user->email_token]));
            Mail::to($user->email)->send($email);
            DB::commit();
            Session::flash(‘message’, ‘We have sent you a verification email!’);
            return back();
            }

            in resources/views/auth/register.blade.php:

            @if (Session::has(‘message’))
            {{ Session::get(‘message’) }}
            @endif

            Right below line 7:

        • Harish

          Created a github repo , you can download and use it directly 🙂
          http://github.com/harishtoshniwal/laravel-53-email-verification

      • BanaanBakje

        Also my RegisterController.php looks like this:

        protected $redirectTo = ‘/home’;

        public function __construct()
        {
        $this->middleware(‘guest’);
        }

        protected function validator(array $data)
        {
        return Validator::make($data, [
        ‘name’ => ‘required|max:255′,
        ’email’ => ‘required|email|max:255|unique:users’,
        ‘password’ => ‘required|min:6|confirmed’,
        ]);
        }

        protected function create(array $data)
        {
        return User::create([
        ‘name’ => $data[‘name’],
        ’email’ => $data[’email’],
        ‘password’ => bcrypt($data[‘password’]),
        ’email_token’ => str_random(10),
        ]);
        }
        Your functions are added below here.

  • Ricardo

    To improve your query time:

    $table->string(’email_token’)->index()->nullable();

  • Hey. I have a question. Did you ever use Socialite with modified Auth? I looking to modify auth to add verification but I also have to use register and log in with Facebook / Twitter. If you did use it, do you have any suggestions? Problems?

    • Harish

      Sorry Kris , haven’t worked with socialite yet , will update you if you need as I will be working with socialite next week 🙂

  • Alexej Kloos

    Thank you very much the blog post. I integrated this feature in my CMS. http://github.com/alcodo/alpaca

    I added some function:
    – phpUnit test
    – Notification email sending
    – Workflow: User became a email after the registration with a event handling

    • Harish

      Woah this looks cool 🙂 Thanks Alexej , glad that this blog helped you 🙂

  • mohamed azarudeen

    thanks for the article
    everything works fine how to check the user verified their email or not

    • Harish

      In the Users table , we have a column “verified” that stores 0 and 1 i.e. false & true respectively. You can make your checks using that value.

  • mohamed azarudeen

    please reply how to check the whether user email is verified or not

    • just go to the database and see whether the verified field is null or one. If it is one, the user is verified

  • Hi guys,
    After I register, my register page gets refreshed only. There is no redirect at login as it used to be before I implemented this method. Note that everything is stored in DB as it should be. Any ideas?

  • Reza Tanzifi

    Thanks for your help. But there is an error that i can not solve. after filling registration form and click on submit it shows me this error :
    Class ‘AppMailEmailVerification’ not found
    what’s wrong????

    • Harish

      Hey Reza , sorry for the late response but i created a boilerplate for the same purpose you can pull it and start working :
      http://github.com/lubusIN/laravel-53-email-verification

    • Vijay Rana

      I am getting the same error. How did you solve it Reza?

      • Harish

        Hey have you added “use AppMailEmailVerification;” at the top of the RegisterController and also have you generated the EmailVerification class using the php artisan command as shown in the blog ?

  • Billa

    Thanks it’s perfect working for me now!!! Thanks lot!!!

    • Harish

      Your welcome 🙂

  • Frank Eugen

    I have added this code to my site, but i get this mass assignment error for email_token although i have included it on fillable array on user model

    • Harish

      Have you added the email_token field in database as well? Silly question but just confirming. Also are you implementing this in a fresh Laravel install?

      • Frank Eugen

        yes i have implemented it on a fresh laravel installation, i have added it in database as well

        • Frank Eugen

          MassAssignmentException in Model.php line 444:
          email_token
          protected $fillable = [
          ‘name’, ’email’, ‘password’, ’email_token’, ‘verified’
          ];

          • Harish

            Can you create a gist of your user.php & register controller , so I can have a look at the code because so far everything seems perfect. And if you have time constraints you can directly download the boilerplate that I created from here : http://github.com/lubusIN/laravel-email-verification-app-boilerplate (v5.3 is on the v5.3 branch , master is the 5.4 version)
            If you want to learn & find out why the error is there you can post the gists so I can recheck & let you know.

          • Frank Eugen
          • Harish

            Check the gist , I have posted my comment there below 🙂

          • Frank Eugen

            Thank you @harishtoshniwal:disqus, i am checking it

  • Hamid Vetr

    thanks a lot it worked perfectly

    • Harish

      Welcome Hamid 🙂 Glad it helped you.

  • Almas

    i cant find the view file (emails.verification) and there is nothing at
    ::
    http://gist.github.com/harishtoshniwal/fd90755ea7fdbb4400cae06808985a68

    • Harish

      Oops sorry! updated the correct link in the blog as well & here it is : http://gist.github.com/introwit/fd90755ea7fdbb4400cae06808985a68 , thank you Almas for pointing that out 🙂

      • Almas

        Thanks a lot, it works fine.. just got a ssl error and sloved… overall its a nice and useful tute

        • Harish

          Glad it helped you Almas 🙂

  • Thanks for you all working correct

  • Help to understand how to change the theme of the letter where I can change that here it is circled in red

    here is image

    http://savepic.ru/12802566.jpg

    • Harish

      Hey pajusalu that email subject is by default the class name you gave while running the php artisan make:mail command , for example if you give the command as php artisan make:mail HelloWorld , the subject (the part you circled in red in the image) will be ‘Hello World’ . You can easily change that in the app/mail/emailVerification.php ‘s build() method by writing the following In it.

      return $this->view(’emails.verification’)
      ->subject(‘Text you want’);

      Hope this helps , let me know if this helps you 🙂

  • Michael Joshua

    Bro, project is working perfectly in localhost, but how I deploy this to server, every mail is dispatch to mailtrap isn’t it, what settings should use to make it to to their respective individual accounts. I am using hostinger server

    • Harish

      You need to use a service like mailgun for that 🙂 Laravel docs on the same topic – http://laravel.com/docs/5.4/mail

      • Michael Joshua

        Ok Thanx Bro, I will look into it

  • Niloufar T

    I followed your instruction but deal with this error

    Connection could not be established with host mailtrap.io [Connection timed out #110]
    what should I do?

    • Harish

      Have you filled the correct mailtrap configurations in your env file and configured the mail.php file? If still the problem persists for you, can you put the contents of both the files in a gist , so I can look at them & identify the issue?

      • Niloufar T

        MAIL_DRIVER=”smtp”
        MAIL_HOST=”mailtrap.io”
        MAIL_PORT=2525
        MAIL_USERNAME=my username
        MAIL_PASSWORD=my password
        MAIL_ENCRYPTION=null
        and same data in mail.php

        in another way I send my mail but went in spam so I want to try mailtrap that cause this problem

        • Harish

          You should type in your mailtrap username & password in quotes as well. I hope you might have already,but still recheck. Other than everything looks good to me. If you still face the problem I would suggest using this boilerplate I made : http://github.com/lubusIN/laravel-email-verification-app-boilerplate

          • Niloufar T

            Harish I typed them

            MAIL_DRIVER=”smtp”
            MAIL_HOST=”mailtrap.io”
            MAIL_PORT=2525
            MAIL_USERNAME=aede72b6e5885a
            MAIL_PASSWORD=559d13425bda26
            MAIL_ENCRYPTION=null
            I’ll try your link but I think that It’s because of my port because of some search result .If I solve my problem I aware u:)

          • Harish

            Put the quotes “” around your mailtrap username & password, that’s what I am saying. Also delete the comment coz it contains your password and that’s not safe 🙂

          • Niloufar T

            🙂 I did it but there is same problem.
            Thanks

          • Harish

            Oh okay! Then it seems an issue with the port. Let me know if it gets sorted

          • Niloufar T

            Hi Dear Harish I solved my port problem and when i send my email It seems that email send even I checked my inbox in mailtrap it has that email but it doesn’t send when i check my mail :O what’s your idea?

          • Harish

            Sorry, can you be more clear? What I can understand is you are saying that When you send the mail, its there in the MailTrap inbox but not it in the Actual gmail inbox?

          • Niloufar T

            That’s it:) I’m checking mailtrap setting right now.Do you have any suggestion?

          • Harish

            Mailtrap is just for testing purposes, for sending actual mails you need a mail service. More here: http://laravel.com/docs/5.4/mail

          • Niloufar T

            My mail service is ok because when I use another port 587 email will be send just goes spam.
            thanks Harish If I find a solution, I will share with u:)

          • Niloufar T

            Every thing is ok right now. my matter solved by changing the port .
            Thank u so much for your trouble and attention:)

  • BobbiMonsta

    I followed all the instructions but in the view the $user doesn’t have any data, I mean, $user->name is null so I don’t have the token in the view either

  • Michael Joshua

    Bro need your help, your registration code is not working in laravel 5.4.14, email_token is always posting as NULL,

  • Michael Joshua

    Also in laravel 5.4.14, in the AppServiceProvider.php boot method, I had to place this code, Schema::defaultStringLength(191);, the problem lies here, in your demo package you used laravel 5.4.3. From Laravel 5.4.6 and above, I am facing problem. Any solution will be greatly appreciated

  • Michael Joshua

    Email token is registering as null in db. I was having a headache, finally tried it in a new laravel 5.3 it worked perfectly, facing problem from 5.4.6 onwards

  • harun tuncay

    Great Tutorial. 1 addition, for those who get an error like -> “email_token can not be null”, change

    $table->string(’email_token’) to $table->string(’email_token’)->nullable();

  • Niverd Manzanilla Antolinez

    Hi friend, I run the entire tutorial step by step, but I get this error when I try to test it

    FatalThrowableError in web.php line 14: Parse error: syntax error, unexpected ‘{‘

    line14;

    Route::get(‘register/verify/{token}’, ‘AuthRegisterController@verify’);

    • Biang Rebyekk

      please check “Route::get(‘register/verify/{token}’, ‘AuthRegisterController@verify’);” carefully, especially when you copied and pasted, better you retype again the ‘ (quote) directly after you copied and pasted.

  • Leandrit Ferizi

    Quite helpful. thanks

    • Harish

      Glad it helped you, your welcome Leandrit 🙂

  • Good article Harish going to implement it soon.

    • Harish

      Thanks Ahmed 🙂 Let me know your thoughts after implementation and if you face any issues while implementing, always here to help.

  • mang ujang

    wher i put this

    Route::get(‘register/verify/{token}’, ‘AuthRegisterController@verify’);

    • nicktr84

      in web.php

  • Hedy

    Thanks for the code Harish. I noticed that when you try to login without verification, the login form will only return credentials error. To solve this on vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php in login function add:

    $user = DB::table(‘users’)->where(’email’, $request->email)->first();
    if($user->verified == 0){
    Session::flash(‘message’, ‘Please check your email for verification!’);
    return redirect()->back()
    ->withInput($request->only($this->username(), ‘remember’));
    }

    Then use DB & Session. And don’t forget to add session message on your login blade.

    @if (Session::has(‘message’))
    {{ Session::get(‘message’) }}
    @endif

  • Mujeeb Mebron

    Thanks a lot, simple code and its worked perfectly.

  • Thanks you so much! It worked for me too. You can announce the Registered event after DB::commit() and maybe do other things that follow.
    event(new Registered($user));

  • bharathi

    hi..how can we add messages to this code.like after registration we have to show one message like “we have sent you a one verification code..please check it once.. like this..

  • HAFIZ MUHAMMAD AHMAD

    Hello, I have Build the API in Laravel 5.4 and Now i need to add Confirmation Mail Process and I am Getting Confuse , kindly Help how i should add The Confirmation Mail.?

  • oxygenyoyo

    how to return message error to the user not verified email yet ? I got return error ‘These credentials do not match our records.’ all the time. That’s not what I expect, so I expect got message something like ‘Your account has not verified yet. ‘

    How to do that ?

    • oxygenyoyo

      I’ve found the solution you open file ‘Auth/LoginController.php’ then add function

      protected function sendFailedLoginResponse(Request $request)
      {
      $errors = [$this->username() => trans(‘auth.failed’)];

      // Load user from database
      $user = AppUser::where($this->username(), $request->{$this->username()})->first();
      // Check if user was successfully loaded, that the password matches
      // and active is not 1. If so, override the default error message.
      if ($user && Hash::check($request->password, $user->password) && $user->verified != 1) {
      $errors = [‘verified’ => ‘error message’];
      }

      if ($request->expectsJson()) {
      return response()->json($errors, 422);
      }

      return redirect()->back()
      ->withInput($request->only($this->username(), ‘remember’))
      ->withErrors($errors);
      }

  • YARAGNI

    I followed your tuto to Add Email Verification In laravel 5.3 App. After following step by step i have this error : #InvalidArgumentException in FileViewFinder.php line 137: View [view.name] not found.# Someone can help me please

  • Aanand Shekhar Roy

    Hey Harish, Thanks for the tutorial. I am having a strange issue though. I am unable to register a user. It redirects to the login page but doesn’t make entry to the user database.

    • Harish

      You have the database credentials set in .env right? And also are the fillable fields are set on the user model?

      • Aanand Shekhar Roy

        Thanks for the prompt reply. Yes, It’s working fine if I don’t override the register method in RegisterController.

        • Harish

          Can you paste the register method of your copy here or in a gist so I can have a look

          • Aanand Shekhar Roy

            Hey Thanks, working fine. I was under the impression that the user’s database entry is made in create function, but actually it happens in register function. Thanks a lot for this great tutorial 🙂

          • Harish

            No problem, have fun 🙂

  • ¤Flex¤VersE¤

    1/1
    ErrorException in EmailVerification.php line 22:
    Undefined variable: user

    in EmailVerification.php line 22at HandleExceptions->handleError(‘8’, ‘Undefined variable: user’, ‘/home/vagrant/web-proj/classpedal/app/Mail/EmailVerification.php’, ’22’, array())

    I am getting that above error when i try to sign up..

    Below is my EmailVerification.php

    namespace AppMail;

    use AppUser;
    use IlluminateBusQueueable;
    use IlluminateMailMailable;
    use IlluminateQueueSerializesModels;
    use IlluminateContractsQueueShouldQueue;

    class EmailVerification extends Mailable
    {
    use Queueable, SerializesModels;

    /**
    * Create a new message instance.
    *
    * @return void
    */
    public function __construct()
    {
    $this->user = $user;
    }

    /**
    * Build the message.
    *
    * @return $this
    */
    public function build()
    {
    return $this->view(’emails.verification’);
    }
    }

    • Harish

      You need to declare the class property first. You are saying “$this->user = xyz”, but this class doesn’t has any property (variable in this case) called ‘user’ in which you can store ‘xyz’. Re-read: If the “this” class doesn’t has any “user” so how can you say $this->user = something? So you need to declare it first. Add “public $user;” before your constructor. Look above in the blog in the EmailVerification.php gist for reference. I hope it helps, let me know if you have any other doubts 🙂

      • ¤Flex¤VersE¤

        Thank you so much Harish.. you made me realise my stupidity…

        • Harish

          No its not stupidity, this is how we learn. Making mistakes is necessary and the first step to learn 🙂 Never underestimate yourself!

      • ¤Flex¤VersE¤

        Works like a charm!! thanks!

  • Michael Joshua

    If a user registers and does not confirm his email, and tries to login, how can i inform user, that he has to confirm email. can you help me?
    I am using laravel 5.4.27.

  • jrean

    Super tutorial!
    I wrote this package to speed up the process:
    http://github.com/jrean/laravel-user-verification

  • Ahmad Izhar

    hello i am working in Laravel Lumen and Lumen do not supports these commands ? Any idea What to do ??

  • Abubakar Waryah

    There are following error when i register the user i am using laravel 5.4 How i can fix it?
    Expected response code 250 but got code “530”, with message “530 5.7.1 Authentication required

  • Mizanur Rahman

    How to solve this error ?

    Argument 1 passed to
    AppHttpControllersAuthLoginController::credentials() must be an
    instance of AppHttpControllersAuthRequest, instance of
    IlluminateHttpRequest given, called in G:laravel
    projectactivityvendorlaravelframeworksrcIlluminateFoundationAuthAuthenticatesUsers.php
    on line 76 and defined

    • Harish

      Add “use IlluminateHttpRequest;” at the top in your LoginController

  • Bang adam

    (1/1)
    MassAssignmentException

    email_token

    i’m getting this error, how to solve this?

  • Waqar Amjad

    can we use it in laravel authentication api…?

  • Pingback: Laravel Authentication - The Missing Pieces - PHP & Laravel Developer()