For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Laravel Middleware - Infovistar

Laravel Middleware

The middleware acts as a bridge between a request and a response. Middleware provides the method to filter HTTP requests that get entered into your project.

Laravel includes a middleware that verifies whether the user of the application 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 in the app/Http/Middleware directory.

Creating a Middleware

Step 1 – Let us now create an AgeChecker. To create a Middleware, we need to execute the following command −

php artisan make:middleware AgeChecker

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

Laravel creating a middleware

Step 3 – AgeChecker Middleware will be created in app/Http/Middleware. The newly created file will have the following code already created for you.

<?php

namespace App∖Http∖Middleware;

use Closure;

class AgeChecker
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Registering Middleware

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

  • Global Middleware - This middleware is run during every request to your application.
  • Middleware Groups - Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware.
  • Route Middleware - This middleware may be assigned to groups or used individually.

The middleware can be registered in app/Http/Kernel.php. This file contains three properties $middleware, $middlewareGroups and $routeMiddleware.

protected $middleware = [
        // App∖Http∖MiddlewareTrustHosts::class,
        ∖App∖Http∖Middleware∖TrustProxies::class,
        ∖Fruitcake∖Cors∖HandleCors::class,
        ∖App∖Http∖Middleware∖CheckForMaintenanceMode::class,
        ∖Illuminate∖Foundation∖Http∖Middleware∖ValidatePostSize::class,
        ∖App∖Http∖Middleware∖TrimStrings::class,
        ∖Illuminate∖Foundation∖Http∖Middleware∖ConvertEmptyStringsToNull::class,
    ];

To register the group-specific middleware, add the key and value to the $middlewareGroups property.

protected $middlewareGroups = [
        'web' => [
            ∖App∖Http∖Middleware∖EncryptCookies::class,
            ∖Illuminate∖Cookie∖Middleware∖AddQueuedCookiesToResponse::class,
            ∖Illuminate∖Session∖Middleware∖StartSession::class,
            // ∖Illuminate∖Session∖Middleware∖AuthenticateSession::class,
            ∖Illuminate∖View∖Middleware∖ShareErrorsFromSession::class,
            ∖App∖Http∖Middleware∖VerifyCsrfToken::class,
            ∖Illuminate∖Routing∖Middleware∖SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            ∖Illuminate∖Routing∖Middleware∖SubstituteBindings::class,
        ],
    ];

To register the route-specific middleware, add the key and value to the $routeMiddleware property.

protected $routeMiddleware = [
        'auth' => ∖App∖Http∖Middleware∖Authenticate::class,
        'auth.basic' => ∖Illuminate∖Auth∖Middleware∖AuthenticateWithBasicAuth::class,
        'bindings' => ∖Illuminate∖Routing∖Middleware∖SubstituteBindings::class,
        'cache.headers' => ∖Illuminate∖Http∖Middleware∖SetCacheHeaders::class,
        'can' => ∖Illuminate∖Auth∖Middleware∖Authorize::class,
        'guest' => ∖App∖Http∖Middleware∖RedirectIfAuthenticated::class,
        'password.confirm' => ∖Illuminate∖Auth∖Middleware∖RequirePassword::class,
        'signed' => ∖Illuminate∖Routing∖Middleware∖ValidateSignature::class,
        'throttle' => ∖Illuminate∖Routing∖Middleware∖ThrottleRequests::class,
        'verified' => ∖Illuminate∖Auth∖Middleware∖EnsureEmailIsVerified::class,
    ];

We have created AgeChecker middleware in the previous example. We can now register it in route-specific middleware property. The code for that registration is as follows:

protected $routeMiddleware = [
        'auth' => ∖App∖Http∖Middleware∖Authenticate::class,
        'auth.basic' => ∖Illuminate∖Auth∖Middleware∖AuthenticateWithBasicAuth::class,
        'bindings' => ∖Illuminate∖Routing∖Middleware∖SubstituteBindings::class,
        'cache.headers' => ∖Illuminate∖Http∖Middleware∖SetCacheHeaders::class,
        'can' => ∖Illuminate∖Auth∖Middleware∖Authorize::class,
        'guest' => ∖App∖Http∖Middleware∖RedirectIfAuthenticated::class,
        'password.confirm' => ∖Illuminate∖Auth∖Middleware∖RequirePassword::class,
        'signed' => ∖Illuminate∖Routing∖Middleware∖ValidateSignature::class,
        'throttle' => ∖Illuminate∖Routing∖Middleware∖ThrottleRequests::class,
        'verified' => ∖Illuminate∖Auth∖Middleware∖EnsureEmailIsVerified::class,
        'age' => ∖App∖Http∖Middleware∖AgeChecker::class,
    ];

Middleware Parameters

We can also pass the parameters with the Middleware. For example, if your application has different roles like the user, branch admin, super admin, etc. and you want to authenticate the action based on the role, this can be possible by passing parameters with middleware.

The AgeChecker middleware that we have created contains the following function and we can pass our custom argument after the $next argument.

public function handle($request, Closure $next) {
   return $next($request);
}

Step 1 − Create RoleMiddleware by executing the following command −

php artisan make:middleware RoleMiddleware

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

Laravel role middleware

Step 3 − Add the following code in the handle method of the newly created RoleMiddleware in app/Http/Middleware/RoleMiddleware.php.

<?php

namespace App∖Http∖Middleware;

use Closure;

class RoleMiddleware {
    public function handle($request, Closure $next, $userRole) {
        echo "User role: ".$userRole;
        return $next($request);
    }
}

Step 4 − Register the RoleMiddleware in the app/Http/Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.

protected $routeMiddleware = [
        'auth' => App∖Http∖MiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => App∖Http∖MiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'age' => App∖Http∖MiddlewareAgeChecker::class,
        'role' => App∖Http∖MiddlewareRoleMiddleware::class,
    ];

Step 5 − Execute the following command to create RoleController−

php artisan make:controller RoleController

Step 6 − After successful execution of the above step, you will receive the following output −

Laravel create role controller

Step 7 − Copy the following lines of code to the app/Http/Controllers/RoleController.php file.

<?php

namespace App∖Http∖Controllers;

use Illuminate∖Http∖Request;

class RoleController extends Controller {
    public function index() {
      echo "
Welcome to Infovistar";
   }
}

Step 8 − Add the following line of code in the app/routes/web.php file.

Route::get('role',[
   'middleware' => 'role:editor',
   'uses' => 'RoleController@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.

Laravel role controller output

Terminable Middleware

Terminable middleware executes some tasks after the response has been sent to the browser. This can be achieved by creating a middleware with the terminate() method in the middleware. Terminable middleware must be registered with global middleware. The terminate method will receive two arguments $request and $response. The terminate() method can be created as follows.

Step 1 − CreateTerminateMiddlewareby executing the below command.

php artisan make:middleware TerminateMiddleware

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

Laravel terminable middleware

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

<?php

namespace App∖Http∖Middleware;

use Closure;

class TerminateMiddleware {

    public function handle($request, Closure $next) {
        echo "Executing the statements of handle method of TerminateMiddleware.";
        return $next($request);
    }

    public function terminate($request, $response) {
        echo "
Executing the statements of terminate method of TerminateMiddleware.";
    }
    
}

Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file.

protected $routeMiddleware = [
        'auth' => App∖Http∖MiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => App∖Http∖MiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'age' => App∖Http∖MiddlewareAgeChecker::class,
        'role' => App∖Http∖MiddlewareRoleMiddleware::class,
        'terminate' => App∖Http∖MiddlewareTerminateMiddleware::class,
    ];

Step 5 − Execute the following command to create TerminateController.

php artisan make:controller TerminateController

Step 6 − After the successful execution of the command, you will get the following output −

Laravel terminate controller

Step 7 − Copy the following code to the app/Http/Controllers/TestController.php file.

<?php

namespace App∖Http∖Controllers;

use Illuminate∖Http∖Request;

class TerminateController extends Controller {
    
    public function index() {
        echo "Terminable Controller.";
    }

}

Step 8 − Add the following line of code in the app/routes/web.php file.

Route::get('terminate',[
   'middleware' => 'terminate',
   'uses' => 'TerminateController@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.

Laravel terminable middleware output