How to Implement Email Verification with Activation Code in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Email verification is a very basic step in the registration process of many applications. If have implemented email configuration in your project then you get lots of benefit like you can forgot password function properly, if user will add wrong content or any Spam in your site then you can contact easily.

If you want to also implement email verify after user registration then you can simply implement in your laravel application. you just follow few step and get email Verification with Activation Code in your project. In this example you can add from scratch, so if you haven't work with laravel then also you can do it simply.

Preview:

Step 1: Laravel Installation

If you haven't installed laravel in your system then you have to run bellow command and get new Laravel project.

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

After clone laravel application, we also require to install laravelcollective/html for Form class, you can install from here : HTML/FORM not found in Laravel 5?.

Step 2: Create Auth using scaffold

In this step, we have to create authentication module using laravel scaffold command. you can create auth very simple just using bellow command. So run bellow command. After run this command you will find layout view of login page, register page and forgot password page.

php artisan make:auth

Step 3: Create Migration

We have to require to add new table and one column in users table. Firstly we need a boolean field 'is_activated' in users table to keep track of whether to determine user is active or deactive. we also need to create new table "user_activations" that will store token of user activation code so we can chack at email varification link time. So first create migration using bellow command:

php artisan make:migration create_users_activation_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create user_activations table.

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateUserActivationsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('user_activations', function (Blueprint $table) {

$table->increments('id');

$table->integer('id_user')->unsigned();

$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');

$table->string('token');

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

});


Schema::table('users', function (Blueprint $table) {

$table->boolean('is_activated');

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::drop("user_activations");


Schema::table('users', function (Blueprint $table) {

$table->dropColumn('is_activated');

});

}

}

Step 4: Add Route

In this step, we have to add new route that hepls to create activation like. we will send mail after registration with activation link that way user can click on that link and active their account.

app/Http/routes.php

Route::get('user/activation/{token}', 'Auth\AuthController@userActivation');

Step 5: Add Controller

This is very important step because we will manage all email configuration function from AuthController.

In this controller first i overwrite register() that way we can write our own code So, first i check validation if any validation fail then it will redirect back, otherwise we will insert new record in users table with is_activated = 0 and also we will send mail with activation link, so if you don't know how to configuration of mail then you can see here : How to set gmail configuration for mail in Laravel?.

In this controller i also overwrite login() that way we can also check if user is not active then we can redirect back with proper message. i also added userActivation() that will check token is valid or not, if token will valid then it will active user and redirect on login page.

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use App\User;

use Validator;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ThrottlesLogins;

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Illuminate\Http\Request;

use DB;

use Mail;


class AuthController extends Controller

{

/*

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

| Registration & Login Controller

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

|

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

| authentication of existing users. By default, this controller uses

| a simple trait to add these behaviors. Why don't you explore it?

|

*/


use AuthenticatesAndRegistersUsers, ThrottlesLogins;


/**

* Where to redirect users after login / registration.

*

* @var string

*/

protected $redirectTo = '/';


/**

* Create a new authentication controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware($this->guestMiddleware(), ['except' => 'logout']);

}


/**

* 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|max:255',

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

'password' => 'required|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']),

]);

}


/**

* Create a new user instance after a valid registration.

*

* @param array $data

* @return User

*/

protected function login(Request $request)

{

$this->validate($request, [

'email' => 'required|email',

'password' => 'required',

]);


if (auth()->attempt(array('email' => $request->input('email'), 'password' => $request->input('password'))))

{

if(auth()->user()->is_activated == '0'){

$this->logout();

return back()->with('warning',"First please active your account.");

}

return redirect()->to('home');

}else{

return back()->with('error','your username and password are wrong.');

}

}


/**

* Register new user

*

* @param array $data

* @return User

*/

public function register(Request $request)

{

$input = $request->all();

$validator = $this->validator($input);


if ($validator->passes()) {

$user = $this->create($input)->toArray();

$user['link'] = str_random(30);


DB::table('user_activations')->insert(['id_user'=>$user['id'],'token'=>$user['link']]);


Mail::send('emails.activation', $user, function($message) use ($user) {

$message->to($user['email']);

$message->subject('Site - Activation Code');

});


return redirect()->to('login')

->with('success',"We sent activation code. Please check your mail.");

}


return back()->with('errors',$validator->errors());

}


/**

* Check for user Activation Code

*

* @param array $data

* @return User

*/

public function userActivation($token)

{

$check = DB::table('user_activations')->where('token',$token)->first();


if(!is_null($check)){

$user = User::find($check->id_user);


if($user->is_activated == 1){

return redirect()->to('login')

->with('success',"user are already actived.");

}


$user->update(['is_activated' => 1]);

DB::table('user_activations')->where('token',$token)->delete();


return redirect()->to('login')

->with('success',"user active successfully.");

}


return redirect()->to('login')

->with('warning',"your token is invalid.");

}

}

Step 6: Add Message in View

This one is last, you have to just add bellow code in your login.blade.php file that way we can display proper message like if mail send successfully and user active successfully.

resources/views/auth/login.blade.php

@if ($message = Session::get('success'))

<div class="alert alert-success">

<p>{{ $message }}</p>

</div>

@endif


@if ($message = Session::get('warning'))

<div class="alert alert-warning">

<p>{{ $message }}</p>

</div>

@endif

resources/views/emails/activation.blade.php

Hi, {{ $name }}


Please active your account : {{ url('user/activation', $link)}}

Try this one....

Shares