Define Middleware

As the name suggest, Middleware acts as a middle man between request and response. It is a type of filtering mechanism. For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.

Middleware can be created by executing the following command −

php artisan make:middleware <middleware-name>

Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Example

Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −

php artisan make:middleware AgeMiddleware

Step 2 − After successful execution of the command, you will receive the following output −

Step 3 − AgeMiddlware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.

Register Middleware

We need to register each and every middleware before using it. There are two types of Middleware in Laravel.

Global Middleware

Route Middleware

The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

To register the global middleware, list the class at the end of $middleware property.

Middleware Parameters

We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $nextargument.

Step 9 − Visit the following URL to test the Middleware with parameters

http://localhost:8000/role

Step 10 − The output will appear as shown in the following image.

Terminable Middleware

Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with“terminate” method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.

Example

Step 1 − Create TerminateMiddleware by executing the below command.

php artisan make:middleware TerminateMiddleware

Step 2 − This will produce the following output −

Step 3 − Copy the following code in the newly created TerminateMiddlewareat app/Http/Middleware/TerminateMiddleware.php.