Laravel 11 Middleware Configuration: A Comprehensive Guide

Outline

Introduction
Getting Started
Global Middleware

prepend() and append()
remove()
replace()
use()

Middleware Groups

group()
prependToGroup() and appendToGroup()
removeFromGroup()
replaceInGroup()

Convenience Methods for W…


This content originally appeared on DEV Community and was authored by Bilal Haidar

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();


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);


  • 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);




replace()

Replace one middleware with another:



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




use()

Define the entire global middleware stack:



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




Middleware Groups

group()

Define a new middleware group:



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




prependToGroup() and appendToGroup()

Add middleware to an existing group:



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




removeFromGroup()

Remove middleware from a group:



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




replaceInGroup()

Replace middleware within a group:



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




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: []
);




Middleware for Static Pages

pages()

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



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




Middleware Aliases and Priority

alias()

Create aliases for middleware:



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




priority()

Define the execution order of middleware:



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




Configuring Specific Middleware

encryptCookies()

Configure the cookie encryption middleware:



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




validateCsrfTokens()

Configure CSRF token validation:



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




validateSignatures()

Configure URL signature validation:



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




convertEmptyStringsToNull()

Configure empty string conversion:



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




trimStrings()

Configure string trimming:



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




trustHosts()

Enable and configure trusted hosts middleware:



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




trustProxies()

Configure trusted proxies:



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




preventRequestsDuringMaintenance()

Configure maintenance mode exceptions:



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




API-Specific Configuration

statefulApi()

Enable Sanctum's stateful API:



$middleware->statefulApi();




throttleApi()

Configure API rate limiting:



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




throttleWithRedis()

Use Redis for throttling:



$middleware->throttleWithRedis();




Session Authentication

authenticateSessions()

Enable session authentication for the 'web' group:



$middleware->authenticateSessions();




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!


This content originally appeared on DEV Community and was authored by Bilal Haidar


Print Share Comment Cite Upload Translate Updates
APA

Bilal Haidar | Sciencx (2024-10-04T16:30:26+00:00) Laravel 11 Middleware Configuration: A Comprehensive Guide. Retrieved from https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/

MLA
" » Laravel 11 Middleware Configuration: A Comprehensive Guide." Bilal Haidar | Sciencx - Friday October 4, 2024, https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/
HARVARD
Bilal Haidar | Sciencx Friday October 4, 2024 » Laravel 11 Middleware Configuration: A Comprehensive Guide., viewed ,<https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/>
VANCOUVER
Bilal Haidar | Sciencx - » Laravel 11 Middleware Configuration: A Comprehensive Guide. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/
CHICAGO
" » Laravel 11 Middleware Configuration: A Comprehensive Guide." Bilal Haidar | Sciencx - Accessed . https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/
IEEE
" » Laravel 11 Middleware Configuration: A Comprehensive Guide." Bilal Haidar | Sciencx [Online]. Available: https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/. [Accessed: ]
rf:citation
» Laravel 11 Middleware Configuration: A Comprehensive Guide | Bilal Haidar | Sciencx | https://www.scien.cx/2024/10/04/laravel-11-middleware-configuration-a-comprehensive-guide/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.