Managing Middleware Priority in Laravel: The New Dynamic Approach

Managing Middleware Priority in Laravel: The New Dynamic Approach

Need to manage your middleware execution order programmatically? Laravel's HTTP Kernel now offers new methods to handle middleware priority with precision! Let's explore these powerful additions.

The New Priority Methods

Laravel introduces two methods for managing middleware priority:

// Add middleware after a specific middleware
$kernel->addToMiddlewarePriorityAfter(
    \Illuminate\Routing\Middleware\ValidateSignature::class,
    [
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
    ]
);

// Add middleware before a specific middleware
$kernel->addToMiddlewarePriorityBefore(
    \Illuminate\Routing\Middleware\ValidateSignature::class,
    [
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
    ]
);

Real-World Example

Here's how you might use this in a package service provider:

class PackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);

        // Add our custom logging middleware after authentication
        $kernel->addToMiddlewarePriorityAfter(
            \Illuminate\Auth\Middleware\Authenticate::class,
            [
                \App\Http\Middleware\LogUserActions::class,
                \App\Http\Middleware\TrackUserSession::class,
            ]
        );

        // Add our security checks before any route handling
        $kernel->addToMiddlewarePriorityBefore(
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            [
                \App\Http\Middleware\ValidateSecurityHeaders::class,
                \App\Http\Middleware\CheckMaintenanceBypass::class,
            ]
        );
    }
}

This new approach makes it easier for package developers to integrate their middleware without requiring manual intervention from users. It's all about making middleware management more flexible and maintainable.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe