How to implement Email Verification with Activation Code in Laravel ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you How to implement Email Verification with Activation Code in Laravel ? We are know that email verification is a very basic step for the registration process of many web applications. If we have implemented our email configuration in our project then we can get a lots of benefit like we can use for forgot password function properly, if any user add any wrong content or any Spam in our site then we can easily contact with them.

If we want to implement email verify after the user registration then we can do this simply by implement in our laravel web application. Just you need to follow the few step and get the email Verification with Activation Code in our project. So now in this example we can add from the scratch, so if you haven’t work with laravel then i hope you can do it also simply.

Step 1: Laravel Installation

If you haven’t installed any laravel in your system then you have install new project by using bellow command and get a new Laravel project.

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

So after clone the laravel application, we also need to install laravelcollective/html for using Form class, we can know how to install from here : HTML/FORM not found in Laravel ?

Step 2: Create Auth using scaffold

Now in this step, we need to create an authentication module by using laravel scaffold command. We can create auth very simple just by using the bellow command.

So need to run bellow command. After run this command we will find a layout view of login page, register page and also forgot password page.

php artisan make:auth
Step 3: Create Migration

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

php artisan make:model CreateUsersActivation

So after this command we will find one file in the following path database/migrations and we have to put the bellow code in our migration file for create the 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

Now in this step, we need to add a new route that helps to create a activation like. We will send a mail after registration with the activation link on that way any user can click on that link and can active their account.

app/Http/routes.php

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

Now this this is a very important step because now we will manage all the email configuration function from AuthController.

Now in this controller at first i will overwrite a register() on that way we can write our own code So, at first i will check the validation if any validation to fail then it will redirect back, otherwise we will insert the new record in users table with is_activated = 0 and also we will send the mail with activation link.

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

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use App\Models\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

Now we are in last step, we have to just add the bellow code in our login.blade.php file on that way we can display the proper message as like if mail send successfully and the 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)}}

Read Also : How to Create Custom Blade Directive in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →