Email verification is essential for many applications to ensure the authenticity of registered users and secure their accounts. In Laravel 11, enabling email verification is straightforward, with built-in tools to make the process easy.
In this guide, I'll show you how to set up email verification in Laravel 11 with clear steps, code snippets, and customizations.
How to Add Email Verification in Laravel 11
This step is optional. However, if you haven't created a Laravel application yet, you can do so by running the following command:
composer create-project laravel/laravel example-app
In this step, we will create an authentication scaffold to generate the login, registration, and dashboard functionalities. Run the following command:
composer require laravel/ui
Laravel Auth:
php artisan ui bootstrap --auth
npm install
npm run build
Now, we need to uncomment the Illuminate\Contracts\Auth\MustVerifyEmail
namespace and implement the MustVerifyEmail
interface in the User model. Let’s do this in the User.php
model file.
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
/** @use HasFactory */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
Here, you need to enable the email verification routes and add middleware to the home route. Let’s update the routes file as follows:
app/Models/User.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Auth::routes([
"verify" => true
]);
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware("verified");
Add or configure the following email settings in your env file to match your email provider.
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io # or smtp.yourprovider.com
MAIL_PORT=2525 # or 587 for Gmail, etc.
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@example.com
MAIL_FROM_NAME="${APP_NAME}"
You might also like: