What is middleware in Laravel?


The middleware is a protection layer in laravel. It helps to filter the http request coming down. It acts as the middle layer between request and response.

For example − Laravel will check if the user logged in is an authenticated user or not. The request has to pass through the middleware .If it's an authenticated user the user will get a pass otherwise it will be logged out.

Another example of using middleware is age restriction. If the user is failing under a certain age range, allow the user to get a few pages otherwise not.

The middleware folder is available inside app/Http/.

You can create middleware using the following command −

php artisan make:middleware<middleware-name>

Let us create AgeMiddleware as shown below −

php artisan make:middleware AgeMiddleware

The code inside AgeMiddleware is as follows −

We have added the code echo "<h1>Inside Age MiddleWare</h1>"; inside the handle function, so that the message is displayed when we use middleware.

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class AgeMiddleware { public function handle(Request $request, Closure $next) { echo "<h1>Inside Age MiddleWare</h1>"; return $next($request); } }

To make use of middleware we need to register it. There are three types of middleware available.

Global Middleware

The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties: $middleware ,$middlewareGroupsand $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

To register the global middleware, list the class at the end of $middleware property. Inside $middleware add the AgeMiddleware we just created as shown below −

protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Fruitcake\Cors\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \App\Http\Middleware\AgeMiddleware::class, ];

If you want to apply the middleware to the entire website it best to declare it globally inside $middleware.

RouteMiddleWare

Let us now use the already create AgeMiddleware on a route . For that we need to add the AgeMiddleware to the routemiddleware variable as shown below −

protected $routeMiddleware = [ 'auth' =>\App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' =>\Illuminate\Auth\Middleware\Authorize::class, 'guest' =>\App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' =>\Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' =>\Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' =>\Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'Age'=>\App\Http\Middleware\AgeMiddleware::class, ];

GroupMiddleware

You can make use of groupmiddleware on a bunch of route pages. We have already created /homepage and /logout page , let us add one more /userpage to the routes we already created.

Now let us add the AgeMiddleware created to groupmiddleware array as shown below −

protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'mypage'=>[ \App\Http\Middleware\AgeMiddleware::class, ] ];

Let us now test global middleware in our application. Since global middleware is applied at all places we should get the message added in Agemiddleware everywhere.

<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class AgeMiddleware { public function handle(Request $request, Closure $next) { echo "<h1>Inside Age MiddleWare</h1>"; return $next($request); } }

You check for any route you should see the global middleware getting called.

Updated on: 01-Sep-2022

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements