Laravel 5 email verification with activation code example

By Hardik Savani November 5, 2023 Category : PHP Laravel

Email verification is a very basic and important part of secure laravel 5 application. In this tutorial i will let you know how to adding email verify step by step using jrean/laravel-user-verification in laravel 5 application.

Several days ago i posted for email verification without package, you can read from here : How to implement Email Verification with Activation Code example from Scratch in Laravel 5.2 ?. So in this post i will share with you email verify using jrean/laravel-user-verification package. You have to simple follow bellow step. In this example i created auth, middleware, email settings etc. So you have to simple follow bellow few step as listed:

Step 1: Install Laravel 5 Fresh Project

Step 2: Create Authentication Module

Step 3: Install jrean/laravel-user-verification Package

Step 4: Create Middleware

Step 5: Overwrite RegisterController

Step 6: Use Middleware and Alert


After finish all step, you will get layout like as bellow screen shot:

Layout:

Step 1: Install Laravel 5 Fresh Project

in this article, we are going from scratch so first download laravel fresh new project with clean code, so it will download new laravel current version. So let's run bellow command.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Authentication Module

here, we will create authentication module using laravel scaffold command. you can create auth very simple just using bellow command. So run bellow command. so let's run bellow command.

php artisan make:auth

After run above command you will find layout view of login page, register page and forgot password page. So also run default migration for users table by bellow command:

php artisan migrate

Step 3: Install jrean/laravel-user-verification Package

Now, we are going to install jrean/laravel-user-verification package for email verify, So let's simple run bellow command to install package:

composer require jrean/laravel-user-verification

After successfully install package, open config/app.php file and add service provider.

config/app.php

'providers' => [

....

Jrean\UserVerification\UserVerificationServiceProvider::class,

],

'aliases' => [

....

'UserVerification' => Jrean\UserVerification\Facades\UserVerification::class,

]

......

Now we have to publish configure file by using bellow command, so let's run bellow command:

php artisan vendor:publish --provider="Jrean\UserVerification\UserVerificationServiceProvider" --tag="config"

Now you will get new configuration file on following path : config/user-verification.php

Also we require to run default migration for jrean/laravel-user-verification package and it will add verified and verification_token column, So let's run bellow command:

php artisan migrate --path="/vendor/jrean/laravel-user-verification/src/resources/migrations"

Step 4: Create Middleware

In this step, we will create custom middleware for checking login user is verified or not so let's run bellow command to create new custom middleware:

php artisan make:middleware IsVerified

app/Http/Middleware/IsVerified.php

<?php


namespace App\Http\Middleware;


use Closure;

use Session;


class IsVerified

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle($request, Closure $next)

{

if(!auth()->user()->verified){

Session::flush();

return redirect('login')->withAlert('Please verify your email before login.');

}

return $next($request);

}

}

app/Http/Kernel.php

<?php


namespace App\Http;


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel

{

....

protected $routeMiddleware = [

....

'isVerified' => \App\Http\Middleware\IsVerified::class,

];

}

Step 5: Overwrite RegisterController

Now we have to overwrite register controller because we are going to add email verification code on register method so just let add bellow code on that file:

app/Http/Controller/Auth/RegisterController.php

<?php


namespace App\Http\Controllers\Auth;


use App\User;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Validator;

use Illuminate\Foundation\Auth\RegistersUsers;


use Jrean\UserVerification\Traits\VerifiesUsers;

use Jrean\UserVerification\Facades\UserVerification;

use Illuminate\Http\Request;


class RegisterController extends Controller

{

/*

|--------------------------------------------------------------------------

| Register Controller

|--------------------------------------------------------------------------

|

| This controller handles the registration of new users as well as their

| validation and creation. By default this controller uses a trait to

| provide this functionality without requiring any additional code.

|

*/


use RegistersUsers;

use VerifiesUsers;


/**

* Where to redirect users after registration.

*

* @var string

*/

protected $redirectTo = '/home';


/**

* Create a new controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('guest',['except' => ['getVerification', 'getVerificationError']]);

}


/**

* Get a validator for an incoming registration request.

*

* @param array $data

* @return \Illuminate\Contracts\Validation\Validator

*/

protected function validator(array $data)

{

return Validator::make($data, [

'name' => 'required|string|max:255',

'email' => 'required|string|email|max:255|unique:users',

'password' => 'required|string|min:6|confirmed',

]);

}


/**

* Create a new user instance after a valid registration.

*

* @param array $data

* @return User

*/

protected function create(array $data)

{

return User::create([

'name' => $data['name'],

'email' => $data['email'],

'password' => bcrypt($data['password']),

]);

}


public function register(Request $request)

{

$this->validator($request->all())->validate();

$user = $this->create($request->all());

UserVerification::generate($user);

UserVerification::send($user, 'My Custom E-mail Subject');

return back()->withAlert('Register successfully, please verify your email.');

}

}

Step 6: Use Middleware and Alert

In this step, we have to use "isVerified" middleware in your HomeController Like as bellow example code, We will use two middleware one for auth and another for user is valid or not.

public function __construct()

{

$this->middleware(['auth','isVerified']);

}

Next, we will add alert session variable print for notification so you have to add bellow code on register.blade.php file:

resources/views/auth/register.blade.php

@if(Session::has('alert'))

<div class="alert alert-success">

{{ Session::get('alert') }}

@php

Session::forget('alert');

@endphp

</div>

@endif

Now we are ready to run this example, before run this example. you have to make sure email configuration. So if you haven't do before then follow bellow link :

Email Configuration.

You can get more information about jrean/laravel-user-verification package from here : jrean/laravel-user-verification.

I hope it can help you...

Tags :
Shares