Middleware filters/modify the http request before entering into the application.
Middleware files are located in app/Http/Middleware folder.
We use Middleware for Checking the request(like Authentication), modifying request data according to requirement before reaching the controller.
We register(or consume) middleware in two ways. One is global and another is route specific.>
1) For registering middleware for all http requests(global), put the middleware class name in $middleware property in app/Http/Kernel.php file.
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
2) For registering middleware for specific route, put the middleware class name with keyname in $routeMiddleware and user middleware() method to apply on specific route.
For example: put middleware class name with keyname in $routeMiddleware(app/Http/Kernel.php)
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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,
];
After putting the middleware class name with keyname we can apply the middleware on route like
Route::get('/about', function(){
return view('about');
})->middleware('auth');
We can use $middlewareGroups to group multiple middleware class in a single key. We can see laravel comes with default $middlewareGroups
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' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
We can use web keyname in route like
Route::get('/', function () { // })->middleware('web');
On the root(/) route all middleware classes applying which is written web array.
How to create custom Middleware
Use php artisan command to create custom middleware
php artisan make:middleware