Deep dive into middlewares in Laravel
Date: Tue, 09-Jan-2018By: Nwanze Franklin
What is a Laravel middleware?
It is a feature in Laravel which provides a mechanism for filtering HTTP requests entering your application. This allows you to hook into Laravel request processing work flow to perform some kind of logic that decides how your application works.
What would you use middleware for?
- Protecting your routes
- Setting headers on HTTP responses
- Logging requests to your application
- Sanitizing incoming parameters
- Enable site-wide maintenance mode
- Manipulating responses generated by your application
How to create a custom middleware?
Creating a middleware in Laravel is as simple as running the following command.
This creates a middleware with the specified name in the middleware folder located in app.
Luckily, Laravel scaffolds the basic things needed to start customizing your middleware.
handle function which accepts two parameters
$next . The
$request parameter holds the incoming request URI in your application while
$next parameter is used to pass the request deeper into the application. The logic needed is written within the handle function and that brings us to types of middleware-
before middleware and
Before middleware as the name suggests handles some set of logic before forwarding the request deeper into the application. On the other hand
after middleware runs after the request has been handled by the application and the response built.
Categories of Middleware
- Global middleware
- Route middleware
Global middlewares run for every single request that hits the application. Laravel comes with most of these middlewares such as
Route middlewares run only on routes they are attached to e.g
Registering a Middleware
Any middleware created has to be registered as that is the only way Laravel knows that such exists. To register a middleware simply open the file named
kernel.php which is located inside Http folder like so:
This file contains list of all registered middlewares that come with Laravel by default. it contains three major arrays which include
Post A Comment