- Laravel - Action URL
- Laravel - Dump Server
- Laravel - Pagination Customizations
- Laravel - Artisan Commands
- Laravel - Guest User Gates
- Understanding Release Process
- Laravel - Hashing
- Laravel - Encryption
- Laravel - Artisan Console
- Laravel - Authorization
- Laravel - Authentication
- Laravel - CSRF Protection
- Laravel - Contracts
- Laravel - Facades
- Laravel - Event Handling
- Laravel - Error Handling
- Laravel - Ajax
- Laravel - Sending Email
- Laravel - File Uploading
- Laravel - Validation
- Laravel - Session
- Laravel - Localization
- Laravel - Forms
- Laravel - Errors & Logging
- Laravel - Working With Database
- Laravel - Redirections
- Laravel - Blade Templates
- Laravel - Views
- Laravel - Response
- Laravel - Cookie
- Laravel - Request
- Laravel - Controllers
- Laravel - Namespaces
- Laravel - Middleware
- Laravel - Routing
- Laravel - Configuration
- Laravel - Application Structure
- Laravel - Installation
- Laravel - Overview
- Laravel - Home
Laravel Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Laravel - Middleware
Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel.
Laravel includes a middleware that verifies whether the user of the apppcation is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects 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
Observe the following example to understand the middleware mechanism −
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 − AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.
<?php namespace AppHttpMiddleware; use Closure; class AgeMiddleware { pubpc function handle($request, Closure $next) { return $next($request); } }
Registering 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 apppcation, 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, pst the class at the end of $middleware property.
protected $middleware = [ IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class, AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, ];
To register the route specific middleware, add the key and value to $routeMiddleware property.
protected $routeMiddleware = [ auth => AppHttpMiddlewareAuthenticate::class, auth.basic => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, guest => AppHttpMiddlewareRedirectIfAuthenticated::class, ];
Example
We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.
The following is the code for app/Http/Kernel.php −
<?php namespace AppHttp; use IlluminateFoundationHttpKernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class, AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, ]; protected $routeMiddleware = [ auth => AppHttpMiddlewareAuthenticate::class, auth.basic => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, guest => AppHttpMiddlewareRedirectIfAuthenticated::class, Age => AppHttpMiddlewareAgeMiddleware::class, ]; }
Middleware Parameters
We can also pass parameters with the Middleware. For example, if your apppcation has different roles pke 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 $next argument.
pubpc function handle($request, Closure $next) { return $next($request); }
Example
Step 1 − Create RoleMiddleware by executing the following command −
php artisan make:middleware RoleMiddleware
Step 2 − After successful execution, you will receive the following output −

Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.
<?php namespace AppHttpMiddleware; use Closure; class RoleMiddleware { pubpc function handle($request, Closure $next, $role) { echo "Role: ".$role; return $next($request); } }
Step 4 − Register the RoleMiddleware in appHttpKernel.php file. Add the pne highpghted in gray color in that file to register RoleMiddleware.

Step 5 − Execute the following command to create TestController −
php artisan make:controller TestController --plain
Step 6 − After successful execution of the above step, you will receive the following output −

Step 7 − Copy the following pnes of code to app/Http/TestController.php file.
app/Http/TestController.php
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class TestController extends Controller { pubpc function index() { echo "<br>Test Controller."; } }
Step 8 − Add the following pne of code in app/Http/routes.php file.
app/Http/routes.php
Route::get( role ,[ middleware => Role:editor , uses => TestController@index , ]);
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 accomppshed 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 − The above step will produce the following output −

Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.
<?php namespace AppHttpMiddleware; use Closure; class TerminateMiddleware { pubpc function handle($request, Closure $next) { echo "Executing statements of handle method of TerminateMiddleware."; return $next($request); } pubpc function terminate($request, $response) { echo "<br>Executing statements of terminate method of TerminateMiddleware."; } }
Step 4 − Register the TerminateMiddleware in appHttpKernel.php file. Add the pne highpghted in gray color in that file to register TerminateMiddleware.

Step 5 − Execute the following command to create ABCController.
php artisan make:controller ABCController --plain
Step 6 − After the successful execution of the URL, you will receive the following output −

Step 7 − Copy the following code to app/Http/ABCController.php file.
app/Http/ABCController.php
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class ABCController extends Controller { pubpc function index() { echo "<br>ABC Controller."; } }
Step 8 − Add the following pne of code in app/Http/routes.php file.
app/Http/routes.php
Route::get( terminate ,[ middleware => terminate , uses => ABCController@index , ]);
Step 9 − Visit the following URL to test the Terminable Middleware.
http://localhost:8000/terminate
Step 10 − The output will appear as shown in the following image.
