Laravel custom email verification, I’ll show you how to set up custom email verification in Laravel. This example walks you through manually verifying emails. With custom email verification, you can modify the email template, generate a personalized verification link, control redirection after verification, and much more. I’ve broken down the process into easy, step-by-step instructions to help you implement email verification in Laravel smoothly
Laravel Custom Email Verification Example
This example demonstrates how to manually verify emails in Laravel. With custom email verification, you have the flexibility to:
- Personalize the email template
- Create a custom verification link
- Handle redirection after successful email verification
- Add other custom features as needed
Laravel comes with a built-in email verification feature by default. However, if you prefer to implement your own custom email verification process, this example will guide you through the steps to do so, providing a step-by-step approach for email verification in Laravel.
- Install Laravel Applications
- Email Configuration
- Create “verify_users” table
- Create Route
- Create Model
- Create Controller
- Create Middleware
- Create Blade File
- Run Application
Step 1: Install Laravel Application
If you already have a Laravel application, you can skip this step. Otherwise, open your terminal and run the following command to create a new Laravel application.
composer create-project laravel/laravel custom-email-verification
Step 2: Email Configuration
In this step, we will configure the email SMTP details in the .env
file
MAIL_DRIVER=smtp
MAIL_HOST="" // add your host here
MAIL_PORT=587
MAIL_USERNAME= // add your user name here
MAIL_PASSWORD= // add your password here
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=""
Step 3: Create “verify_users” table
We will create the “verify_users” table and add a new column, “is_email_verified,” to the users table.
php artisan make:migration create_verify_users_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class VerifyUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('verify_users', function (Blueprint $table) {
$table->integer('user_id');
$table->string('token');
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_email_verified')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Step 4: Create Route
We have created our custom routes in the routes/web.php
file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\AuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('login', [AuthController::class, 'index'])->name('login');
Route::post('post-login', [AuthController::class, 'postLogin'])->name('login.post');
Route::get('registration', [AuthController::class, 'registration'])->name('register');
Route::post('post-registration', [AuthController::class, 'postRegistration'])->name('register.post');
Route::get('logout', [AuthController::class, 'logout'])->name('logout');
/* New Added Routes */
Route::get('dashboard', [AuthController::class, 'dashboard'])->middleware(['auth', 'is_verify_email']);
Route::get('account/verify/{token}', [AuthController::class, 'verifyAccount'])->name('user.verify');
Step 5: Create Model
We need to add the “is_email_verified” field to the fillable array in the User model and create a new model called VerifyUser, as shown below:
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
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'is_email_verified'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class VerifyUser extends Model
{
use HasFactory;
public $table = "verify_users";
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'user_id',
'token',
];
/**
* Write code on Method
*
* @return response()
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Step 6: Create Controller
We need to create an AuthController. In this controller, we have updated the code in the postRegistration()
and verifyAccount()
methods. Let’s copy the code as shown below:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use App\Models\VerifyUser;
use Hash;
use Illuminate\Support\Str;
use Mail;
class AuthController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
return view('auth.login');
}
/**
* Write code on Method
*
* @return response()
*/
public function registration()
{
return view('auth.registration');
}
/**
* Write code on Method
*
* @return response()
*/
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('You have successfully logged in');
}
return redirect("login")->withSuccess(You have entered invalid credentials!');
}
/**
* Write code on Method
*
* @return response()
*/
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$createUser = $this->create($data);
$token = Str::random(64);
VerifyUser::create([
'user_id' => $createUser->id,
'token' => $token
]);
Mail::send('email.emailVerificationEmail', ['token' => $token], function($message) use($request){
$message->to($request->email);
$message->subject('Email Verification Mail');
});
return redirect("dashboard")->withSuccess(You have Ssuccessfully logged in');
}
/**
* Write code on Method
*
* @return response()
*/
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess(You do not have access!');
}
/**
* Write code on Method
*
* @return response()
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Write code on Method
*
* @return response()
*/
public function logout() {
Session::flush();
Auth::logout();
return Redirect('login');
}
/**
* Write code on Method
*
* @return response()
*/
public function verifyAccount($token)
{
$verifyUser = User::where('token', $token)->first();
$message = 'Sorry your email cannot be identified.';
if(!is_null($verifyUser) ){
$user = $verifyUser->user;
if(!$user->is_email_verified) {
$verifyUser->user->is_email_verified = 1;
$verifyUser->user->save();
$message = "Your e-mail is verified. You can now login.";
} else {
$message = "Your e-mail is already verified. You can now login.";
}
}
return redirect()->route('login')->with('message', $message);
}
}
Step 7: Create Middleware
We need to create a middleware to check whether the user’s email is verified. Let’s create it as shown below:
php artisan make:middleware VerifyEmailId
app/Http/Middleware/VerifyEmailId.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class VerifyEmailId
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!Auth::user()->is_email_verified) {
auth()->logout();
return redirect()->route('login')
->with('message', 'You need to confirm your account. We have sent you an activation code, please check your email.');
}
return $next($request);
}
}
app/Http/Kernel.php
protected $routeMiddleware = [
....
'verify_email_id' => \App\Http\Middleware\VerifyEmailId::class,
];
Step 8 : Create Blade File
resources/views/emails/emailVerification.blade.php
<h1>Email Verification</h1>
Please verify your email with bellow link:
<a href="{{ route('user.verify', $token) }}">Verify Email</a>
Hope it can help you
Thanks