How to enable email verification support in Laravel

Razet · · 3143 Views

As we all know, an email confirmation is a must-have feature for the most web application. That is the inbuilt solution for us after the Laravel v5.7 release, and we can easily implement this into Laravel projects.

So let’s get started:

Create a new Laravel Project

Run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel my-app-name

Database Setup:

Update database credentials in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=user
DB_PASSWORD=password

Next, run the migration command to create tables in the database:

php artisan migrate

If you look at the database, you should get tables created accordingly and most specifically check out the users table, it has a new field added from Laravel that is email_verified_at. It is going to store date-time value when the user has verified their email.

Frontend Scaffolding

If you are using Laravel version below v6 then just run php artisan make:auth and it is done, your frontend scaffolding is ready.

If your Laravel version is v6 or above first you have to install laravel/ui package. To install it run the following command in your terminal:

composer require laravel/ui

After that, to install the frontend scaffolding run the following command:

php artisan ui bootstrap --auth

In the views directory, you will see a blade file that is resources/views/auth/verify.blade.php. This is view user is going to see when they are logged in but not verified there email address.

Prepare User Model

Next, we need to update the User model to implement MustVerifyEmailContract.

<?php

namespace App;
 
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract;
 
class User extends Authenticatable implements MustVerifyEmailContract
{
    use Notifiable;
 
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];
 
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Enable Verification on Routing

Next will have to provide a parameter to the Auth::routes(); to add an email verification route.

<?php
 
Route::get('/', function () {
    return view('welcome');
});
 
Auth::routes(['verify' => true]);
 
Route::get('/home', 'HomeController@index')->name('home');

Protect Routes

Laravel has new route middleware available for us. To use that simply do the same as we always do when whenever we use middleware with the controller, add new verified middleware into the constructor as showing below:

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }
 
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }
}

Email Driver Setup

Next, you need to set up email drivers for the project, there are several ways are provided in Laravel such as SMTP, Mailgun, Mandrill, Sparkpost, etc.

Update the .env file with your preferred email driver.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Test Email Verification Support

Now every configuration is done. And it's time to test it. So, create a new account see how does this implementation works. 

After register, you should get redirected to the verify view, where it says verify your email address. Check your email inbox for the verification email. Click the verification link and you will be redirected to the home page.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar