How to Create Global Middleware in Laravel

AuthorSumit Dey Sarkar

Pubish Date19 Mar 2023


In this tutorial we will learn how to create global middleware in laravel.


How to create global middleware in laravel

In Laravel, you can create global middleware by following these steps:


1) Open the `App\Http\Kernel.php` file in your Laravel application.


2) Locate the `$middleware property` in the class. This property contains an array of middleware that will be applied to every HTTP request handled by your application.


3) Add your middleware class or its fully-qualified namespace to the `$middleware` array. For example, if your middleware class is named `MyGlobalMiddleware`, you can add it to the `$middleware` array like this:

protected $middleware = [
    // Other middleware...

If you prefer, you can also use a string containing the fully-qualified namespace of your middleware class instead of the class reference.


4) Save the `Kernel.php` file.


Now, every HTTP request handled by your Laravel application will pass through your global middleware before being handled by the application's routes or controllers. Note that the order of the middleware in the $middleware array matters, so make sure your global middleware is added in the correct order.

Comments 0

Leave a comment