How to prioritize middleware in Laravel

Have you ever wanted to execute your middleware according to priorities? Let’s say you have four middlewares and you want to first check if the user has been authenticated, meaning the user has paid and has permission to execute a specific action in this sequence. Laravel makes this not only possible but also easy.

Let’s dive in

First, arrange your middleware according to your priority using $middlewarePriority property in your app/Http/Kernel.php file. You may need to create the property in your HTTP kernel by copying and pasting the code code:

protected $middlewarePriority = [
    \Illuminate\Cookie\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

Then add your middleware to the ones in the array. You should avoid changing the initial arrangement because Laravel has prioritized arrangements for the middleware with which it ships.

Free Resources