Laravel middleware explained in brief
Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.
Middleware can be written to perform a variety of tasks for example
User authentication, CSRF validation, Application logging, etc...
How to create middleware
All of the middlewares are located in the app/Http/Middleware directory.
Below is the command to create a new middleware,
php artisan make:middleware ValidateToken
Registering Middleware
Global Middleware
If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.
Assigning Middleware To Routes
If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application’s app/Http/Kernel.php
file. By default, the $routeMiddleware
property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choosing:// Within App\Http\Kernel class...
protected $routeMiddleware = [
Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:
'auth' => \App\Http\Middleware\Authenticate::class,
...
...
]Route::get('/profile', function () {
//
})->middleware('auth');
You may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method, The withoutMiddleware method can only remove route middleware and does not apply to global middleware.
You may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In this case, you may specify your middleware priority using the $middlewarePriority property of your app/Http/Kernel.php file.
Middleware can perform tasks before or after passing the request deeper into the application.
For a detailed explanation on middleware visit Laravel documentation