AppDividend
Latest Code Tutorials

Laravel 9 Email Verification: Complete Guide

You need to configure the settings and write some minimal code to set up everything in this version. Email verification is the most functionality in web apps, and laravel makes it very easy. So let us do it then.

Laravel 9 Email Verification

Many web applications require their users or customers to verify their email addresses before using the application. Rather than forcing you to re-implement this on each application, Laravel provides convenient methods for sending and verifying email verification requests. First, let’s see how to verify the user’s email address.

Step 1: Install Laravel and configure the database.

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

# or

laravel new emailVerify

Laravel 5.7 Email Verification Tutorial Example

Go inside the folder.

cd emailVerify

Fire up your favorite IDE or Editor.

code .

Create the MySQL database and write the credentials inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=emailVerify
DB_USERNAME=root
DB_PASSWORD=root

Okay, now migrate the tables by the following command.

php artisan migrate

Now, see the users table, and you can see there is one more field called email_verified_at.

Laravel 5.7 Email Verification

The email_verified_at column is there, which is new in Laravel. So when the user registers and verifies the email, the timestamp will be recorded here. So based on that, we can differentiate whether the user has confirmed the email.

We have generally used the datatype boolean for this kind of functionality, but nowadays, people are using a timestamp to accomplish this kind of goal.

Step 2: Laravel Auth Scaffolding

Okay, now go to the terminal and type the following command.

php artisan make:auth

This command has generated one more view called verify.blade.php. It is new in Laravel as the verification functionality is implemented in this version.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Verify Your Email Address') }}</div>

                <div class="card-body">
                    @if (session('resent'))
                        <div class="alert alert-success" role="alert">
                            {{ __('A fresh verification link has been sent to your email address.') }}
                        </div>
                    @endif

                    {{ __('Before proceeding, please check your email for a verification link.') }}
                    {{ __('If you did not receive the email') }}, <a href="{{ route('verification.resend') }}">{{ __('click here to request another') }}</a>.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 3: Implement must verify interface in the User model.

In the User.php model, you can see one more contract added called  MustVerifyEmail. To use the email verification process, we need to implement this contract.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    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',
    ];
}

Step 4: Add Email Route Verification

Go to the routes >> web.php file and add the extra parameter inside Auth::routes().

Auth::routes(['verify' => true]);

This enables the new Verification controller with the route actions. You can see the new controller called VerificationController.php file already comes with Laravel.

Also, we need to protect the HomeController route, so let us do that via adding middleware.

   /** HomeController.php
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

Step 5: Setup email configuration

I am using mailtrap for this example. So log in to the https://mailtrap.io/signin.

Go to the demo inbox, copy the credentials, and paste them to your .env file.

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

Step 6: Test the email verification functionality.

First, go to the browser and go to either http://localhost:8000/register or, like me, go to the http://emailverify.test/.register. 

You will see the page like this.

Verify Email in Laravel

Now go to the mailtrap, and you can see that verification mail has arrived.

Email Verification in Laravel 5.7

Also, see the database and analyze the users’ table.

Laravel 5.7 Auth Functionality

Here, the email_verified_at is null. Now, click the link that is arrived at your email, and your email will be verified, and you can see here the timestamp will be registered.

Email verified in Laravel

That’s it for the Laravel Email Verification Tutorial. Thanks for taking it.

12 Comments
  1. David Rusnac says

    How do you edit the view of the verification email. The make:auth command doesn’t install a email view but seems to be auto generated.

  2. Ronald says

    Hi, thanks for ” Laravel 5.7 Email Verification Tutorial Example ” but I got a big question, how can I customize the verification email message sent to the user?: “Hello! Please click the button below to verify your email address. ….”

    I heard that is has something to do with “public static $toMailCallback; ” in the VerificationController.php, but I don’t know how to do it.

    Thanks a lot.

  3. MIke says

    There is an error i got on home controller
    */
    public function __construct()
    {
    $this->middleware([‘auth’, ‘verified’]);
    }

    cant pass two argument at the same time

    1. Test says

      Look again at: $this->middleware([‘auth’, ‘verified’]);

      It should be $this->middleware([‘auth’ => ‘verified’]);

  4. Lee says

    Am I the only person who thinks checking for email verification on every request is a bad idea?

    On a secure site where most pages require you to login your more than likely going to want to check Auth and Verified, which means every request to every secure page on your site checks if the user verified their email. Seems crazy to me, another layer to go through every time even if it is a small hit.

    Surly it would make sense to just check this once at login as the default and allow you to use it as middleware if you have that requirement. Plus it feels wrong to have to check both Auth and Verified, I know they are testing different things I just feel verified should be part of Auth once its implemented.

    Maybe I’m missing soothing, but I don’t like it, and I hate having to develop my own version of something that’s bundled. I wish they had made it a composer package so I could choose to use it, or better still not made middleware the default.

  5. Devendra says

    hiiii i found this issue

    Swift_TransportException
    Process could not be started [The system cannot find the path specified. ]

    D:\xampp\htdocs\EmailVerification\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php
    $this->in = &$this->stream;
    $this->out = &$this->stream;
    }

    /**
    * Opens a process for input/output.
    */
    private function establishProcessConnection()
    {
    $command = $this->params[‘command’];
    $descriptorSpec = [
    0 => [‘pipe’, ‘r’],
    1 => [‘pipe’, ‘w’],
    2 => [‘pipe’, ‘w’],
    ];
    $pipes = [];
    $this->stream = proc_open($command, $descriptorSpec, $pipes);
    stream_set_blocking($pipes[2], 0);
    if ($err = stream_get_contents($pipes[2])) {
    throw new Swift_TransportException(
    ‘Process could not be started [‘.$err.’]’
    );
    }
    $this->in = &$pipes[0];
    $this->out = &$pipes[1];
    }

    private function getReadConnectionDescription()
    {
    switch ($this->params[‘type’]) {
    case self::TYPE_PROCESS:
    return ‘Process ‘.$this->params[‘command’];
    break;

    case self::TYPE_SOCKET:
    default:
    $host = $this->params[‘host’];
    if (!empty($this->params[‘protocol’])) {
    $host = $this->params[‘protocol’].’://’.$host;
    }
    Arguments
    “””
    Process could not be started [The system cannot find the path specified.
    ]
    “””

  6. jimmy kaler says

    Good job! Thanks.

  7. Alex says

    Good job ! Thank you

  8. R Barrientos says

    How can I customize the verification mail?

    1. Tom Croft says

      If you want to change the the structure am the notification email, then you can do it this way:

      php artisan vendor:publish –tag=laravel-notifications
      The notification view is published to:

      resources/views/vendor/email.blade.php
      After this, you can go ahead and make any changes to the view. This will apply to all the notifications sent through the app, and not just the verify email one.

      Cheers!

  9. Enea Paja says

    If you have problems with routing the Verification.verify
    {route [verification.verify] not defined} you will need to add these route to
    routes->web
    Route::get(’email/verify’, ‘Auth\VerificationController@show’)->name(‘verification.notice’);
    Route::get(’email/verify/{id}’, ‘Auth\VerificationController@verify’)->name(‘verification.verify’);
    Route::get(’email/resend’, ‘Auth\VerificationController@resend’)->name(‘verification.resend’);

  10. Edie Polpa says

    Hello ,

    I’m getting an error: Interface ‘Illuminate\Contracts\Auth\MustVerifyEmail’ not found.

    Could you please help me how to fix it.

    Thank you in advance

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.