Laravel Middleware Defining a Middleware


Example

To define a new middleware we have to create the middleware class:

class AuthenticationMiddleware
{
    //this method will execute when the middleware will be triggered
    public function handle ( $request, Closure $next )
    {
        if ( ! Auth::user() )
        {
            return redirect('login');
        }

        return $next($request);
    }
}

Then we have to register the middleware: if the middleware should be bind to all the routes of the application, we should add it to the middleware property of app/Http/Kernel.php:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\AuthenticationMiddleware::class
];

while if we only want to associate the middleware to some of the routes, we can add it to $routeMiddleware

//register the middleware as a 'route middleware' giving it the name of 'custom_auth'
protected $routeMiddleware = [
    'custom_auth' => \App\Http\Middleware\AuthenticationMiddleware::class
];

and then bind it to the single routes like this:

//bind the middleware to the admin_page route, so that it will be executed for that route
Route::get('admin_page', 'AdminController@index')->middleware('custom_auth');