Member-only story

Customizing Middleware in Laravel 11

I Nyoman Jyotisa
3 min readNov 2, 2024

--

With Laravel 11, new projects benefit from a more streamlined setup, which includes removing several default middleware classes. So, how do you now customize middleware? It’s simple: adjustments can be made directly in bootstrap/app.php. Let’s walk through the most common customizations.

Common Middleware Customizations

Redirecting Guests to a Custom Page
To set a specific redirect for guests, you can use the redirectGuestsTo() method in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
$middleware->redirectGuestsTo('/admin/login');
})

In earlier versions, this redirection was handled within the Authenticated.php middleware file.

Custom Redirects for Users and Guests
For managing where both users and guests are redirected, utilize the redirectTo() method in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
$middleware->redirectTo(
guests: '/admin/login',
users: '/dashboard'
);
})

Previously, this setup was handled in Authenticated.php and RedirectIfAuthenticated.php.

Exempting Specific Cookies from Encryption
To configure which cookies should not be…

--

--

Responses (1)