This content originally appeared on DEV Community and was authored by Bilal Haidar
Outline
- Introduction
- Getting Started
- Global Middleware
- prepend() and append()
- remove()
- replace()
- use()
- Middleware Groups
- group()
- prependToGroup() and appendToGroup()
- removeFromGroup()
- replaceInGroup()
- Convenience Methods for Web and API Groups
- web() and api()
- Middleware for Static Pages
- pages()
- Middleware Aliases and Priority
- alias()
- priority()
- Configuring Specific Middleware
- encryptCookies()
- validateCsrfTokens()
- validateSignatures()
- convertEmptyStringsToNull()
- trimStrings()
- trustHosts()
- trustProxies()
- preventRequestsDuringMaintenance()
- API-Specific Configuration
- statefulApi()
- throttleApi()
- throttleWithRedis()
- Session Authentication
- authenticateSessions()
- 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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.