Introduction to Default Middleware Customization in Laravel 11
Starting from Laravel 11, new projects now use a streamlined skeleton. This change aims to simplify the default configuration, one of the major shifts being the removal of default middleware classes.
While this might sound like a significant change, the framework provides an easy way to customize middleware directly through the bootstrap/app.php
file. Below are common use cases showing how to configure middleware effectively in Laravel 11.
Customize the Default Middleware
1. Change Where Guests Are Redirected
To customize the redirect location for guests (unauthenticated users), use the redirectGuestsTo()
method in the bootstrap/app.php
file:
Previously, this behavior was defined in the Authenticated.php
middleware.
2. Change Where Users and Guests Are Redirected
You can also customize where both authenticated users and guests are redirected using the redirectTo()
method. This method centralizes the behavior that was previously managed in the Authenticated.php
and RedirectIfAuthenticated.php
middleware files:
3. Exclude Cookies from Being Encrypted
If you need to exclude certain cookies from being encrypted, you can do so by using the encryptCookies()
method:
Previously, this functionality was defined in the EncryptCookies.php
middleware file.
4. Exclude Routes from CSRF Protection
You can specify which routes should be excluded from CSRF protection using the validateCsrfTokens()
method:
This was previously handled by the VerifyCsrfToken.php
middleware file.
5. Exclude Routes from URL Signature Validation
To exclude specific routes from URL signature validation, use the validateSignatures()
method:
Before this, the exclusion logic was found in the ValidateSignature.php
middleware file.
6. Prevent Converting Empty Strings in Requests
In Laravel 11, you can customize the behavior that converts empty strings to null
with the convertEmptyStringsToNull()
method. This replaces the older approach of removing the middleware in app/Http/Kernel.php
or customizing it on a per-route basis:
7. Prevent String Trimming in Requests
You can prevent automatic trimming of strings in requests by using the trimStrings()
method. This method replaces the behavior previously defined in the TrimStrings.php
middleware file:
Conclusion
With Laravel 11’s updated middleware configuration approach, all the customization now takes place centrally within the bootstrap/app.php
file. Whether it’s adjusting where users are redirected, excluding routes from CSRF or URL signature validation, or controlling how cookies and strings are handled, the new system makes it easy to apply changes to your middleware without needing to interact with the app’s default middleware files.