Sling Academy
Home/PHP/How to verify email in Laravel (with examples)

How to verify email in Laravel (with examples)

Last updated: January 16, 2024

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.

Next Article: How to Encrypt Data in Laravel: Tutorial & Examples

Previous Article: SMS Notifications in Laravel: A Practical Guide

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array