Laravel Middleware

Laravel Middleware

Middleware is another essential component of Laravel and provides the method to filter HTTP requests that get entered into your project. Let us assume a situation where this middleware of Laravel checks for an authenticated user of your software or project. In case the authentication is verified as valid, the middleware feature will let the user proceed with your project. There is another middleware name CORS, that is in charge of adding appropriate headers to all of your responses.


Table of Contents
1. Define Middleware
2. Registering Middlewares
3. Middleware Parameters
4. Terminable Middlewares

Define Middleware

Middleware can be defined as a middle-man or interface acting in coordination between a request and a response. As mentioned in the above test scenario, if the user is not authenticated, then your project may redirect that user from login.php to index.php page.

You can create your middleware by running the syntax mentioned below:

Syntax:
php artisan make:middleware<middleware_name>

Here, you have to replace the <middleware_name> with your middleware. You can see this path location app/Http/Middleware the middleware that you will be creating your project.

Example:
php artisan make:middleware CheckUser

Registering Middlewares

Before using any middleware, you have to register it.

Laravel provides two types of Middlewares. These are:
  • Global Middleware
  • Route Middleware

Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.

When you want a middleware to specific routes, you have to add the middleware with a key for your app/Http/Kernel.php file, and such middlewares are called route middleware. $routeMiddleware, by default, holds entries for the middleware that are already incorporated in Laravel. For adding your custom middleware, you need to append them to the list and add a key of your choice.

Example:
rotected $routeMiddleware = [
   'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
   'userAuth' => \Illuminate\Routing\Middleware\UserAuthRequests::class,
];

Middleware Parameters

Parameters can also be passed to middlewares. Various parameterized situations can be something when your project has attributes like a customer, employee, admin, owner, etc. and you want to execute different modules based on the roles of the user, for those situations, parameters of middlewares becomes useful.

Example:
public function handle($request, Closure $next, $profile)
   {
       if (! $request->user()->hasProfile($profile)) {
           // Next page
       }
       return $next($request);
   }
}

You need to create the Profile middleware by running the code mentioned below:

php artisan make:middleware ProfileMiddleware

The newly created middleware can be handled using the code: app/Http/Middleware/ProfileMiddleware.php

Example:
<?php

namespace App\Http\Middleware;
use Closure;

class ProfileMiddleware {
   public function handle($request, Closure $next, $Profile) {
      echo "Role: ".$Profile;
      return $next($request);
   }
}

Terminable Middlewares

These are special types of middlewares that start working right after any response is sent to the browser. The terminate method is used for achieving this. When a terminate method is used in the middleware of your project, it gets called automatically after the browser response is sent.

Example:
<?php

namespace Illuminate\Session\Middleware;
use Closure;
class SessionBegin
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
    public function terminate($request, $response)
    {
        // tasks assigned within terminate method
    }
}
Reactions

Post a Comment

0 Comments

close