Jump to content

No explanation in the Laravel Document about the Middleware


ali_254

Recommended Posts

Hi, in the kernel file, a number of arrays are defined...

    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    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,
        ],


    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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,
    ];

 

But Laravel's document does not explain them, what is the reason?

https://laravel.com/docs/8.x/middleware

Link to comment
Share on other sites

It does explain them. 

While this is not in the manual, Laravel Middleware is an implementation of the Chain or Responsibility OOP Design Pattern.

It is essentially a linked list of classes, each with a handle() method, and the HTTP request gets passed along and the handle() method is run.  Once the handle method is complete, the next() method is called which will run the next handler.  All the handlers are run, unless one of them interrupts the process rather than calling it's next()  method.  

From the manual:

Quote

If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.

So all the middleware handler classes in the $middleware array are run for every HTTP Request.  If you have your own custom middleware you would also want run for every request, the manual page you posted shows you how you write one, which again just has to follow the same rules as any of the other middleware.

Obviously there are other types of handlers that should only be applied to certain applications.  For example, a Web application will likely have very different requirements than a REST api that is used by a Mobile application has.  One very simple example of this difference is that a Web application will probably use cookies, whereas a mobile application will probably use tokens and assume its own local storage and configuration.  Another example would be a web app implemented CSRF protection for web forms, where a mobile app won't have that, because it's not utilizing HTML client forms.  

Quote

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the $middlewareGroups property of your HTTP kernel.

So this is where Laravel groups up a set of associated Middleware handlers generally applicable to one application type.  As you can see the web middleware group comes with the list of handlers you posted.  Again you can add and subtract and customize this.

Quote

f you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choosing:

This is fairly self explanatory I think.  You are just given a convenient tag name for a handler to be used with specific routes to handle things like authentication and permissions.  When defining a route, you are able to specify the list of middleware keys for the specific middleware handlers you need to have processed when that route is accessed.  

There are a few different ways to set up your routes.  So there are some additional middleware options that might be of value, relative to how you defined your routes, especially if you are adding routes to a middleware group.

  • Like 1
Link to comment
Share on other sites

Thanks ... but I want to know, what is the role of Laravel's default middlewares?

 

For example, what is the role of TrustProxies Middleware?

or , ShareErrorsFromSession Middleware , What is its function?

 

Laravel does not mention them in the documents

Link to comment
Share on other sites

Most of these are named in a way that is fairly self explanatory, but sometimes you have to just take a look at the class to see what it is doing.

The last 2 are again, very similar.  Looking at the class definitions from the manual will show you what they do, and the code is simple and self explanatory, especially once you understand the things I explained about how middleware works in Laravel.

See https://laravel.com/api/9.x/index.html and find the 2 classes.

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.