Laravel-Middleware

The middleware acts as a bridge between the request and the response. This is a type of filter mechanism. This chapter describes the middleware mechanism in Laravel.
Laravel includes a middleware that checks if the application user is authenticated or not. If the user is authenticated it redirects to the home page, otherwise if it doesn't redirect to the login page.
The middleware can be created by running the following command:
php artisan make:middleware <middleware-name>
Replace <middleware-name> with the name of your middleware. The middleware you create can be seen in the app/Http/Middleware directory .
example
Pay attention to the following example to understand the middleware mechanism −
Step 1 − Let's now create the AgeMiddleware. To create this, we need to execute the following command −
php artisan make:middleware AgeMiddleware
Step 2 − After running the command successfully, you will get the following output −
Step 3 − AgeMiddleware will be created in Application/Http/Middleware . The newly created file will have the following code already generated for you.
<? php namespace App \Http\Middleware ; use Closure ; class AgeMiddleware { public function handle ( $request , Closure $next ) { return $next ( $request ); } }
Register Middleware
We must register each middleware before using it. There are two types of Middleware in Laravel.
- Global Middleware
- Routing middleware
The global middleware will be executed on every HTTP request by the application, while the route middleware will be assigned to a specific route. Middleware can be registered in app/Http/Kernel.php. This file contains two properties $ middleware and $ routeMiddleware . The $middleware property is used to register the Global Middleware and the $routeMiddleware property is used to register the route specific middleware.
To register global middleware, list the class at the end of the $middleware property.
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ];
To register the middleware for a specific route, add a key and value to the $routeMiddleware property.
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, ];
example
We created the AgeMiddleware in the previous example. Now we can register it in a route-specific middleware property. The code for this registration is shown below.
Following is the code for Application/Http/Kernel.php −
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'Age' => \App\Http\Middleware\AgeMiddleware::class, ]; }
Middleware options
We can also pass parameters using Middleware. For example, if your application has different roles like user, admin, super admin, etc. and you want to authenticate action based on role, this can be achieved by passing parameters using middleware. The middleware we create contains the following function and we can pass our custom argument after the $next argument .
public function handle($request, Closure $next) { return $next($request); }
example
Step 1: Create a RoleMiddleware by running the following command:
php artisan make:middleware RoleMiddleware
Step 2 − Upon successful execution, you will get the following output −
Step 3: Add the following code to the handle method of the newly created RoleMiddlewareat /Http/Middleware/RoleMiddleware.php application .
<?php namespace App\Http\Middleware; use Closure; class RoleMiddleware { public function handle($request, Closure $next, $role) { echo "Role: ".$role; return $next($request); } }
Step 4 − Register RoleMiddleware in app\Http\Kernel.php file . Add the line highlighted in gray in this file to register the RoleMiddleware.
Step 5 − Run the following command to create TestController −
php artisan make:controller TestController --plain
Step 6 − After successfully completing the above step, you will get the following output −
Step 7 − Copy the following lines of code to app/Http/TestController.php file .
app/Http/TestController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class TestController extends Controller { public function index() { echo "<br>TestController."; } }
Step 8 − Add the following line of code to app/Http/rout.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 look as shown in the following image.
Terminable middleware
Interruptible middleware performs some task after the response is sent to the browser. This can be achieved by creating a middleware with a termination method in the middleware. Interruptible middleware must be registered with the global middleware. The terminate method will receive two arguments $request and $response. The Terminate method can be created as shown in the following code.
example
Step 1 − Create TerminateMiddleware by running the following command.
php artisan make:middleware TerminateMiddleware
Step 2 − The above step will produce the following result −
Step 3: Copy the following code to the newly created TerminateMiddleware in app/Http/Middleware/TerminateMiddleware.php.
<?php namespace App\Http\Middleware; use Closure; class TerminateMiddleware { public function handle($request, Closure $next) { echo "Executing statements of handle method of TerminateMiddleware."; return $next($request); } public function terminate($request, $response) { echo "<br>Executing statements of terminate method of TerminateMiddleware."; } }
Step 4 − Register TerminateMiddleware in app\Http\Kernel.php file . Add the line highlighted in gray in this file to register the TerminateMiddleware.
Step 5 − Run the following command to create ABCController .
php artisan make:controller ABCController --plain
Step 6 − After successfully executing the URL, you will get the following output −
Step 7 − Copy the following code to app/Http/ABCController.php file .
app/Http/ABCController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ABCController extends Controller { public function index() { echo "<br>ABC Controller."; } }
Step 8 − Add the following line of code to app/Http/rout.php file .
app/http/routes.php
Route::get('terminate',[ 'middleware' => 'terminate', 'uses' => 'ABCController@index', ]);
Step 9 − Visit the following URL to check Terminable Middleware.
http://localhost:8000/terminate
Step 10 − The output will look as shown in the following image.