Laravel - MiddleWare

Mohamad MahmoodMohamad Mahmood
1 min read

[1] Create middleware

Create a middleware task via php artisan command:

php artisan make:middleware IsVerifyEmail

Define the task:

(app\http\middleware\IsVerifyEmail.php)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class IsVerifyEmail
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::user()->email_verified_at == null) {
            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);
    }
}

[2] Register Middleware to Http Kernel

protected $routeMiddleware = [
    ....
    'is_verify_email' => \App\Http\Middleware\IsVerifyEmail::class,
];

[3] Register Middleware to Route

Route::get('dashboard', [AuthController::class, 'dashboard'])->middleware(['auth', 'is_verify_email']);

References:

https://laravel.com/docs/10.x/middleware

0
Subscribe to my newsletter

Read articles from Mohamad Mahmood directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohamad Mahmood
Mohamad Mahmood

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He studies at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).