Creating Custom middleware in Laravel 5.4

In Laravel Middlewares are used for filter HTTP requests in your application.
In this post we are going to create a simple Middleware to check user has verified his email or not, if user has not verified his email send user to home page with error message.This middleware is used after user will loggedIn in application.I am assuming that you have added a new column is_email_verified in your users table to track the verification of emails.

Below are step by step guide to create custom Middleware.

Creating middleware:

In Laravel you create a new middleware, using the make:middleware Artisan command:

php artisan make:middleware isEmailVerified 

Above command will a new php file named isEmailVerified.php in app/Http/Middleware directory. Open your isEmailVerified.php file and put below code in that.

<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Session;
class isEmailVerified
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       //Checking user is loggedin 
       if(Auth::check()){
         if(Auth::user()->is_email_verified != 1)
            Session::flash('error', 'You have not verified your email yet.');
            return redirect()->route('verify-email');
          }
       }
        return $next($request);
    }
}

?>

Now we need to register and create aliase for our middleware in Kernel.php file so please open app/Http/Kernel.php and add our middleware in $routeMiddleware array.

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
	......
	protected $routeMiddleware = [
        ......
        'isEmailVerified' => \App\Http\Middleware\isEmailVerified::class,
    ];
}
?>

Now our custom Middleware isEmailVerified is ready to use in our app. Apply it in your routes/web.php to use.

Route::get('home', ['as'=>'home','uses'=>'HomeController@index']);

Route::group(['middleware' => 'isEmailVerified'], function () {     
    Route::get('users/dashboard', ['as'=>'dashboard','uses'=>'UsersController@dashboard']); 
});

Leave a Reply

Your email address will not be published. Required fields are marked *