how to add two factor authentication to laravel

Setting up Laravel authentication

Laravel pre-built authentication functionality with a single command

php artisan make:auth
# create the database tables needed with
php artisan migrate
you will now see this. Notice LOGIN and REGISTER at the top of the screen.

Add two factor authentication during registration

when new user send form data for register then we will show new web page with qr code and private key. when user will scan code and click on complete resignation. when we will send a sccret code in database table. QR code will accessible only once so this is very good for security.

Install two packages


composer require pragmarx/google2fa-laravel
composer require bacon/bacon-qr-code

open config/app.php, add to providers array


PragmaRX\Google2FALaravel\ServiceProvider::class,

Add to aliases array.

'Google2FA' => PragmaRX\Google2FALaravel\Facade::class,

now add a new method in registercontroller

public function register(Request $request)
    {
        //first we will validate the incoming request
        $this->validator($request->all())->validate();

        // Initialise the 2FA class
        $google2fa = app('pragmarx.google2fa');

        // store registration data in an array
        $registration_data = $request->all();

        // Create new secret key to the registration data
        $registration_data["google2fa_secret"] = $google2fa->generateSecretKey();

        // store registration data to the user session for new request
        $request->session()->flash('registration_data', $registration_data);

        // Create the QR image. 
        $QR_Image = $google2fa->getQRCodeInline(
            config('app.name'),
            $registration_data['email'],
            $registration_data['google2fa_secret']
        );

        // Send the QR barcode image to our view
        return view('google2fa.register', ['QR_Image' => $QR_Image, 'secret' => $registration_data['google2fa_secret']]);
    }
now create new folder inside view google2fa(name it anything. inside this folder create new blade file - register.blade.php.

now when user will register then register.blade.php file will open with QR code

after scan the code with google Authenticator app click on continue
then you need to add code which displaying on your app
now we need to add new column in mysql users table - google2fa_secret, you can add manually by phpmyadmin and you can add via command also

php artisan make:migration add_google2fa_column_to_users --table=users
php artisan migrate