Check if an email is verified in Laravel
This tutorial will show you how to implement email verification in your laravel application and check if the user has verified his email.
Implement MustVerifyEmail interface
First of all, you need to implement MustVerifyEmail interface in your User Model.
<?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;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, 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',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Add verified middleware to your routes
Next, we need to add the middleware verified to our routes thus only verified users can access them.
Route::get('posts', PostController@create)->middleware('verified');
Check if the user has verified his email
To check if the user email is verified all you need to do is to get the user and use the hasVerifiedEmail() function.
$user = Auth::user();
$user->hasVerifiedEmail();