Laravel middleware explained in brief

HouseOfCoder
2 min readJan 3, 2021

--

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 = [
'auth' => \App\Http\Middleware\Authenticate::class,
...
...
]
Once the middleware has been defined in the HTTP kernel, you may use the middleware method to assign middleware to a route:
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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

HouseOfCoder
HouseOfCoder

Written by HouseOfCoder

Web developer by profession. Crafting code and contemplative thoughts. Join me on a journey of tech, life, and mindfulness.

No responses yet

Write a response