Laravel Middleware: What is it? Code Examples

Ismat Babirli
4 min readJan 19, 2023

Laravel Middleware is an important part of the Laravel framework. It lets developers do things before or after an application handles a request. Middleware acts as a link between an application request and its response. It makes it easy to filter and change both requests and responses.

In Laravel, "middleware" is defined as a class that implements the Middleware interface. These classes are then registered with the application and can be assigned to specific routes or groups of routes. When a request is made to a route that is assigned a middleware, the middleware’s handle method is executed before the request is passed to the controller or closure that handles the route.

One of the most common uses of middleware is for authentication and authorization. For example, middleware can be used to check if a user is logged in before allowing them to access certain routes or pages. Middleware can also be used to perform tasks such as rate limiting, caching, and logging.

Another advantage of middleware is that it can be reused across different routes or controllers. For example, a middleware that checks for a valid API token can be assigned to multiple routes that require authentication. This helps to keep the code clean and maintainable.

There are several built-in middlewares that comes with Laravel, such as the EncryptCookies, RedirectIfAuthenticated, and VerifyCsrfToken middleware. These middleware perform common tasks such as encrypting cookies, redirecting authenticated users, and verifying CSRF tokens.

Creating custom middleware is also very easy. You can use the php artisan make:middleware command to create a new middleware class. Once the class is created, you can define the handle method, which will contain the logic that you want to execute.