How to make two-factor authentication in Laravel

Last Updated: June 6, 2021

In this tutorial you can learn how to implement two-factor authentication in Laravel. You can follow the the steps listed here.

What is two-factor authentication?
Two-factor authentication is a mechanism to provide additional security to your login system. In addition to username and password you have to provide the token which will be sent to your phone as a SMS.

You can use the Auty for two-factor authentication but here we will do it from scratch.

You can follow the following steps.

  1. Install the Laravel
  2. Add custom field to registration form
  3. Add fields to users table
  4. Generate token
  5. Send token to phone
  6. Add PhoneVerification middleware
  7. Create phone verify controller

1 Install the Laravel.

To start this tutorial you can install fresh Laravel project in your web server. If you new to Laravel you can read this tutorial. This has the steps for installation

2 Add custom fields to registration form

We need to add phone field to the registration form. So you can open the
resources\views\auth\register.blade.php and add the following code. This should be placed just below the E-mail field



@if ($errors->has(‘phone’)) {{ $errors->first(‘phone’) }} @endif

Now you can see the Phone field in registration form. You can enter the phone number to receive token via SMS

3 Add extra field to database

We need to add some fields to database for two factor authentication implementation
I am going to add phone field to hold the phone number, code field to store the token sent to the mobile device and isverified field for storing the status of the verification

I am going to use following artisan command to create database migration file

     php artisan make:migration add_extra_field_to_users_table

This will create migration file at database\migrations folder. Now lets add code to add fields

 public function up()
        Schema::table('users', function(Blueprint $table)

     * Reverse the migrations.
     * @return void
    public function down()
        Schema::table('users', function(Blueprint $table)

4 Generate Token

We can use random key generator to generate token

composer require gladcodes/keygen

You have generate the token inside the create method of RegisterController in App\Http\Controllers\Auth

 $key = Keygen::numeric(4)->generate();

5 Send token to phone

Once you generate the token you have to send it to phone and store it in the users table. You can use Nexmo API to send SMS
You can install the php client library

composer require nexmo/laravel

You can add Nexmo\Laravel\NexmoServiceProvider to the providers array in your config/app.php

'providers' => [

 // other code 

You can put the key and secret in your .env file.


Now you can add following code inside the create method to send token via SMS

protected function create(array $data)
       // send sms code

        $key = Keygen::numeric(4)->generate();
            'to'   => $data['phone'],
            'from' => '16105552344',
            'text' => 'Your verifcation code : '.$key
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'code' => $key,
            'password' => bcrypt($data['password']),

This will send the SMS and phone number and token will be stored in users table in database

6 Add PhoneVerification middleware

Upto this point you have generated the token and send to mobile device when user regitser in the application first time.
Now when user tries to open the login page he should be prompted to enter the token and it should be validated with entry in the users table

I will create a middleware to check whether user has verified his phone number with token

To create the middlewre run the following command at your terminal

php artisan make:middleware PhoneVerification

You can add the following code to App\Http\Middleware\PhoneVerification.php file

       if (($user!=null) && ($user->isverified == 0)){
            return redirect('verify');

        return $next($request);

Next I am going to assign this middleware as a route middleware. You can add the following code to Kernal.php file in App\Http

 protected $routeMiddleware = [
        //other code
        'auth' => \App\Http\Middleware\PhoneVerification::class,

7 Create phone verify controller

In this, you can create controller to view the form to enter the token. First we will create the controller and then we will create the view

php artisan make:controller PhoneVerifyController 

Now you can add the following two actions to the controller

public function verify(){
    	return view('verify');

public function verifySubmit(Request $request){
      $user = Auth::user();

    	return redirect("/home");

You can see two action in this code. Action verify() will show you the form and action verifySubmit() will verify the user submitted value

Your routes\web.php file shouls have following entry

Route::get('/verify', 'PhoneVerifyController@verify');
Route::post('/verify', 'PhoneVerifyController@verifySubmit')->name('verify.submit');

Finally resources\views\verify.blade.php will have following code to display the form



<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Phone Verification</div>
<div class="panel-body"><form class="form-horizontal" action="{{ route('verify.submit') }}" method="POST">{{ csrf_field() }}
<div class="form-group{{ $errors->has('codr') ? ' has-error' : '' }}"><label class="col-md-4 control-label" for="email">Enter Code</label>
<div class="col-md-6"><input id="email" class="form-control" name="code" required="" type="text" value="{{ old('code') }}" autofocus=""> @if ($errors-&gt;has('code')) <span class="help-block"> <strong>{{ $errors-&gt;first('code') }}</strong> </span> @endif</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4"><button class="btn btn-primary" type="submit"> Submit </button></div>

You will see the following screen after you login to the system

If you want to know more about Laravel please see out tutorials