Laravel Middleware

To clarify the idea of the Middleware, think of it as an additional layer that filters HTTP requests that come to the server.
If the request is authorized, it allows the request to continue, and if the request is not authorized, your request will die and make a redirect.
There are Middleware that exists by default, such as

  1.  CORS middleware  which is responsible for adding the proper headers to all responses leaving your website

How to create a new middleware

step1: using single artisan command you can  create a new middleware

php artisan make:middleware AnyName

* make sure to change AnyName to your middleware  name 

now the artisan will create a new middleware in app/Http/Middleware directory 

also, your middleware can make some code before or after a request


namespace App\Http\Middleware;

use Closure;

class AnyName
    public function handle($request, Closure $next)

        // add any code before the request 

        $response = $next($request);

        // -- middleware rule

        // add any code after the request 
        return $response;


step2: Defined the middleware in the HTTP kernel

Types of Middlewares in Laravel

In Laravel there are two types of Middlewares:
  • Global Middleware
  • Route Middleware

Global middleware 

it's a middleware that will run during all HTTP request to your application, you can add or edit the Global middleware which registers in $middleware property inapp/Http/Kernel.php  directory 

Route middleware 

this middleware will run in a specific route, not for all request you can add or edit the route middleware which registers in $routeMiddleware property inapp/Http/Kernel.php  directory 

step3: Assign middleware to a route

Route::get('/', function () {