Laravel 11 - Email Verification

Touseef Afridi
17 Sep 24

Laravel 11 - Email Verification

In this tutorial, we'll explore how to verify email addresses in Laravel 11 using Breeze authentication. This enhances security by ensuring users provide valid email addresses.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through setting up email verification in a Laravel application using Breeze authentication. You’ll begin by creating a fresh Laravel project with Breeze to set up authentication. Then, you'll enable email verification in the User model by implementing the MustVerifyEmail contract. To protect routes, you'll apply the verified middleware, ensuring that only users with verified emails can access certain pages. The guide also covers setting up Mailtrap for email testing, updating the .env file with the necessary Mailtrap credentials, and testing the email verification process by registering a new user and verifying their email address. By the end of this guide, you'll have successfully implemented email verification in your Laravel application, ensuring users confirm their email addresses before accessing the app.

Step # 1 : Create a Fresh Laravel Project with Breeze Authentication.

To send a welcome notification email, authentication needs to be set up so that the email can be triggered when a user registers. To simplify this, we'll use Laravel Breeze for authentication when setting up the project.
If Laravel is installed globally, use the following command to create fresh project.
laravel new verify-email
Alternatively, if Laravel is not installed globally, use the Composer command.
composer create-project laravel/laravel --prefer-dist verify-email
After running the command to create the project, you'll be prompted with the following steps.
  • Would you like to install the starter kit? → Select Breeze.
  • After selecting Breeze, you'll be asked to choose your stack? → Select Blade.
  • After selecting Blade, you'll be asked for dark mode support? → Select no.
  • After selecting No, you'll be asked about testing framework? → Select PHPUnit.
  • After selecting PHPUnit, you'll be asked if you want to initialize git repo? → Select no.
  • After selecting no, you'll be asked to select the database for your application? → Select MySQL.
  • After selecting MySql, you'll be asked if you want to run the default database migration? → Select yes.

Once completed, you'll have a fresh Laravel project set up with Breeze Authentication, configured to use MySQL as the database, and the default database migration will have been run automatically. This setup ensures that email verification is in place, allowing users to verify their email addresses upon registration before they can access the application.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/verify-email
This will allow you to run Artisan commands and manage your Laravel project directly from the terminal.

Step # 3 : Enable Email Verification in User model.

To enable email verification, open the User model in app/Models/User.php, uncomment the MustVerifyEmail contract, and implement it within the User class. This ensures that any newly registered user will be required to verify their email before gaining access to the application. Here is the updated code for your User model.
<?php
namespace App\Models;
// Uncomment the contract for MustVerifyEmail
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// Add MustVerifyEmail to the User class
class User extends Authenticatable implements MustVerifyEmail
{
    use HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}
Implementing the MustVerifyEmail contract in the User model ensures that new users must verify their email address before accessing the application, triggering the automatic sending of a verification email. This helps improve security by confirming that the user's email is valid, and it provides a smoother user experience by automating the verification process.

Step # 4 : Protect Routes with Email Verification.

To ensure that certain routes are accessible only to users with a verified email, apply the verified middleware to those routes.
Route::get('/dashboard', function () {
 // Define the route here that requires the user to be authenticated and have a verified email
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Step # 5 : Create a Mailtrap Account.

  1. Visit Mailtrap at: https://mailtrap.io and create an account.
  2. After signing up, create a new project for testing purposes.
  3. Access the testing project, where you'll find all the necessary details for the next step.


Step # 6: Update .env.

To properly configure Mailtrap for email testing in your Laravel application, you'll need to update your .env file with the correct credentials from your Mailtrap account. In your .env file, replace the following placeholders with the actual details from your Mailtrap project.
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME="Your Mailtrap username"
MAIL_PASSWORD="Your Mailtrap password"
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="Your email address"
MAIL_FROM_NAME="${APP_NAME}"
Once you’ve replaced the placeholders with your Mailtrap credentials, save the file. This will allow your application to use Mailtrap’s SMTP server to send test emails without actually delivering them to real inboxes. You can always view the emails sent by your Laravel application within the Mailtrap dashboard for verification. This process ensures that the email functionality is tested in a controlled environment, helping you prevent potential issues with real user emails during development. By using Mailtrap, you can ensure that email functionality is correctly implemented before deploying your application to production.

Step # 7 : Test the Email Verification Process.

Start the Laravel development server by running the following command in your terminal.
php artisan serve
Access the application by visiting the URL: 127.0.0.1:8000. Create a new user account on the registration page.

After registration, you will be redirected to the verify-email page.

You should receive a verification email in your Mailtrap inbox.

Click the Verify Email Address link in the email, and you will be redirected to the dashboard.

Email successfully verified, and you can now access the application, completing the testing of email verification in your Laravel application.

Conclusion

By following this guide, you’ve successfully implemented email verification in your Laravel application using Breeze authentication. Your application now ensures that users must verify their email address before accessing protected routes, enhancing security and user experience. You’ve also learned how to configure Mailtrap for testing email functionality, update the .env file with the correct SMTP credentials, and test the email verification process in a local environment. This setup provides a reliable email verification system, ensuring smooth user registration and access management.
For more details, refer to the Laravel documentation on authentication and email verification.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering