How to verify email in Laravel (with examples)

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Email verification is a critical part of modern web applications to ensure user authenticity and to minimize spam. Laravel, being a powerful PHP framework, provides straightforward methods for email verification. This tutorial walks through the steps required to implement email verification in a Laravel application. We will cover the basics and advance to more complex scenarios, providing code examples and expected outputs where applicable.

Prerequisites

Before proceeding, you should have:

  • A running Laravel application
  • Knowledge of Laravel’s MVC structure
  • A database configured for your application
  • Access to a mail service for sending emails

Basic Setup

Laravel makes it simple to set up basic email verification by using the MustVerifyEmail contract and built-in notifications system. Let’s start by implementing email verification in a fresh Laravel project.

First, ensure that your User model implements the MustVerifyEmail contract:

<?php
namespace App\Models;

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

class User extends Authenticatable implements MustVerifyEmailContract
{
    use Notifiable;

    // ...
}

Next, modify the default route in web.php to include email verification routes:

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

Now, update your registered() function in RegisterController.php (or your equivalent registration controller) to ensure email verification is necessary after registration:

protected function registered(Request $request, $user)
{
    $user->sendEmailVerificationNotification();

    return redirect($this->redirectPath())->with('verified', true);
}

Email Verification Configuration

In your .env file, configure your mailing service details:

MAIL_MAILER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

Laravel will use these details to send verification emails. It’s recommended to use a service like Mailtrap for development purposes to catch and test emails.

Customizing The Email

If you wish to change the look of the verification email, you can do so by customizing the notification. Create a new notification with:

php artisan make:notification VerifyEmailCustom

In the generated VerifyEmailCustom.php, you can customize the email as necessary:

<?php
namespace App\Notifications;

use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
use Illuminate\Notifications\Messages\MailMessage;

class VerifyEmailCustom extends VerifyEmailBase
{
    protected function buildMailMessage($url)
    {
        return (new MailMessage)
            ->subject('Verify Email Address')
            ->line('Please click the button below to verify your email address.')
            ->action('Verify Email Address', $url);
    }
}

To use this custom notification, override the sendEmailVerificationNotification() method in your User model:

public function sendEmailVerificationNotification()
{
    $this->notify(new VerifyEmailCustom);
}

Advanced Scenario: Queueing Verification Emails

To prevent delays during registration, it’s a good idea to queue verification emails. Implement the ShouldQueue interface in your custom notification:

<?php
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;

class VerifyEmailCustom extends VerifyEmailBase implements ShouldQueue
{
    use Queueable;
    // ...
}

Make sure your email-related environment variables support queue workloads.

Testing Email Verification

To test your setup, use Tinker or make an appropriate http request. User email verification status can be checked as follows:

php artisan tinker
> $user = App\Models\User::find(1);
> $user->hasVerifiedEmail();
// Outputs: false

Then, go through the email verification process to see if the status updates:

> $user->markEmailAsVerified();
> $user->hasVerifiedEmail();
// Outputs: true

Conclusion

Laravel’s built-in functionality simplifies email verification. The process can be further customized as per the project requirements. Always ensure that you handle and store user information securely. By following the steps in this guide, you can easily implement a reliable email verification system in your Laravel projects.