DEV Community

Bilal Haidar
Bilal Haidar

Posted on

Laravel 11 Middleware Configuration: A Comprehensive Guide

Outline

  1. Introduction
  2. Getting Started
  3. Global Middleware
    1. prepend() and append()
    2. remove()
    3. replace()
    4. use()
  4. Middleware Groups
    1. group()
    2. prependToGroup() and appendToGroup()
    3. removeFromGroup()
    4. replaceInGroup()
  5. Convenience Methods for Web and API Groups
    1. web() and api()
  6. Middleware for Static Pages
    1. pages()
  7. Middleware Aliases and Priority
    1. alias()
    2. priority()
  8. Configuring Specific Middleware
    1. encryptCookies()
    2. validateCsrfTokens()
    3. validateSignatures()
    4. convertEmptyStringsToNull()
    5. trimStrings()
    6. trustHosts()
    7. trustProxies()
    8. preventRequestsDuringMaintenance()
  9. API-Specific Configuration
    1. statefulApi()
    2. throttleApi()
    3. throttleWithRedis()
  10. Session Authentication
    1. authenticateSessions()
  11. Conclusion

Introduction

Laravel 11 introduces a new way to configure middleware through the Illuminate\Foundation\Configuration\Middleware class. This powerful class provides a fluent interface for managing your application's middleware stack. In this blog post, we'll explore the public methods of this class and demonstrate how to use them effectively in your Laravel application.

Getting Started

In Laravel 11, middleware configuration is typically done in the bootstrap/app.php file. You'll use the withMiddleware method to access the Middleware instance:



use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        // Configure your middleware here
    })
    ->create();


Enter fullscreen mode Exit fullscreen mode

Now, let's dive into the various methods available for configuring middleware.

Global Middleware

prepend() and append()

These methods allow you to add middleware to the global stack:



$middleware->prepend(MyCustomMiddleware::class);
$middleware->append(AnotherMiddleware::class);


Enter fullscreen mode Exit fullscreen mode
  • prepend() adds the middleware to the beginning of the global stack.
  • append() adds the middleware to the end of the global stack.

remove()

Remove middleware from the global stack:



$middleware->remove(UnwantedMiddleware::class);

Enter fullscreen mode Exit fullscreen mode




replace()

Replace one middleware with another:



$middleware->replace(OldMiddleware::class, NewMiddleware::class);

Enter fullscreen mode Exit fullscreen mode




use()

Define the entire global middleware stack:



$middleware->use([
TrustProxies::class,
HandleCors::class,
PreventRequestsDuringMaintenance::class,
ValidatePostSize::class,
TrimStrings::class,
ConvertEmptyStringsToNull::class,
]);

Enter fullscreen mode Exit fullscreen mode




Middleware Groups

group()

Define a new middleware group:



$middleware->group('api', [
'throttle:api',
SubstituteBindings::class,
]);

Enter fullscreen mode Exit fullscreen mode




prependToGroup() and appendToGroup()

Add middleware to an existing group:



$middleware->prependToGroup('web', EnsureUserIsActive::class);
$middleware->appendToGroup('api', LogApiRequests::class);

Enter fullscreen mode Exit fullscreen mode




removeFromGroup()

Remove middleware from a group:



$middleware->removeFromGroup('web', ShareErrorsFromSession::class);

Enter fullscreen mode Exit fullscreen mode




replaceInGroup()

Replace middleware within a group:



$middleware->replaceInGroup('web', StartSession::class, CustomSessionMiddleware::class);

Enter fullscreen mode Exit fullscreen mode




Convenience Methods for Web and API Groups

web() and api()

Modify the default 'web' and 'api' middleware groups:



$middleware->web(
append: [EnsureUserIsActive::class],
prepend: [LogWebRequests::class],
remove: [ShareErrorsFromSession::class],
replace: [StartSession::class => CustomSessionMiddleware::class]
);

$middleware->api(
append: [LogApiRequests::class],
prepend: [RateLimiter::class],
remove: ['throttle:api'],
replace: []
);

Enter fullscreen mode Exit fullscreen mode




Middleware for Static Pages

pages()

Define middleware for static pages (useful with Laravel Folio):



$middleware->pages([
ValidateCsrfToken::class,
SubstituteBindings::class,
]);

Enter fullscreen mode Exit fullscreen mode




Middleware Aliases and Priority

alias()

Create aliases for middleware:



$middleware->alias([
'auth' => Authenticate::class,
'throttle' => ThrottleRequests::class,
]);

Enter fullscreen mode Exit fullscreen mode




priority()

Define the execution order of middleware:



$middleware->priority([
StartSession::class,
ShareErrorsFromSession::class,
ThrottleRequests::class,
SubstituteBindings::class,
]);

Enter fullscreen mode Exit fullscreen mode




Configuring Specific Middleware

encryptCookies()

Configure the cookie encryption middleware:



$middleware->encryptCookies(['unencrypted_cookie']);

Enter fullscreen mode Exit fullscreen mode




validateCsrfTokens()

Configure CSRF token validation:



$middleware->validateCsrfTokens(['/api/*']);

Enter fullscreen mode Exit fullscreen mode




validateSignatures()

Configure URL signature validation:



$middleware->validateSignatures(['/download/*']);

Enter fullscreen mode Exit fullscreen mode




convertEmptyStringsToNull()

Configure empty string conversion:



$middleware->convertEmptyStringsToNull([
fn ($request) => $request->is('api/*')
]);

Enter fullscreen mode Exit fullscreen mode




trimStrings()

Configure string trimming:



$middleware->trimStrings([
'password',
fn ($request) => $request->is('admin/*')
]);

Enter fullscreen mode Exit fullscreen mode




trustHosts()

Enable and configure trusted hosts middleware:



$middleware->trustHosts(fn () => [
'example.com',
'*.example.com',
]);

Enter fullscreen mode Exit fullscreen mode




trustProxies()

Configure trusted proxies:



$middleware->trustProxies('192.168.1.1', Illuminate\Http\Request::HEADER_X_FORWARDED_ALL);

Enter fullscreen mode Exit fullscreen mode




preventRequestsDuringMaintenance()

Configure maintenance mode exceptions:



$middleware->preventRequestsDuringMaintenance(['api/*', 'status']);

Enter fullscreen mode Exit fullscreen mode




API-Specific Configuration

statefulApi()

Enable Sanctum's stateful API:



$middleware->statefulApi();

Enter fullscreen mode Exit fullscreen mode




throttleApi()

Configure API rate limiting:



$middleware->throttleApi('60,1');

Enter fullscreen mode Exit fullscreen mode




throttleWithRedis()

Use Redis for throttling:



$middleware->throttleWithRedis();

Enter fullscreen mode Exit fullscreen mode




Session Authentication

authenticateSessions()

Enable session authentication for the 'web' group:



$middleware->authenticateSessions();

Enter fullscreen mode Exit fullscreen mode




Conclusion

The new Middleware configuration class in Laravel 11 provides a powerful and flexible way to manage your application's middleware. By using these methods, you can easily customize the middleware stack, create groups, set priorities, and configure specific middleware behaviors.

Remember to make these configurations in your bootstrap/app.php file to ensure they're applied correctly throughout your application. Happy coding!

Top comments (0)