Support the ongoing development of Laravel.io →

Customizing Auth Middlewares in Laravel 11

24 Oct, 2024 2 min read 234 views

Photo by Kutan Ural on Unsplash

Customizing Auth Middlewares in Laravel 11

If you've worked with Laravel before, you're probably familiar with authentication redirects like sending guests to the login page or redirecting authenticated users away from pages they shouldn't access. Laravel 11 has introduced a new, simpler way to handle this. In this article, we'll explore how to implement these new auth middleware customizations.

In previous Laravel versions, we had to modify two different middleware classes to customize how users and guests were redirected. Here's what that looked like:

In App/Http/Middleware/RedirectIfAuthenticated.php:

public function handle(Request $request, Closure $next, string ...$guards): Response
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            return $request->user()->isAdmin() ?
                redirect(RouteServiceProvider::ADMIN_HOME) :
                redirect(RouteServiceProvider::HOME);
        }
    }

    return $next($request);
}

And in App/Http/Middleware/Authenticate.php:

protected function redirectTo(Request $request): ?string
{
    return $request->expectsJson() ? null : route('account.login');
}

However, in Laravel 11, we have a new way to customize them. Taylor Otwell, the creator of Laravel, has introduced a much simpler approach. The auth middlewares are now part of Laravel's core (located in Illuminate\Auth\Middleware\) so, like before, we can't modify these middleware classes directly. Instead, we now handle all the configuration in the bootstrap/app.php file.

For unauthenticated users who try to access pages meant for logged-in users, we can redirect them using redirectGuestsTo:

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

    // Or using a closure...
    $middleware->redirectGuestsTo(fn (Request $request) => route('account.login'));
})

For authenticated users who visit guest-only pages like login or register, we can redirect them using redirectUsersTo:

->withMiddleware(function (Middleware $middleware) {
    $middleware->redirectUsersTo('/account/dashboard');

    // Or for more complex logic, like different dashboards for different user types...
    $middleware->redirectUsersTo(fn (Request $request) =>
        $request->user()->isAdmin()
            ? route('admin.dashboard')
            : route('account.dashboard')
    );
})

This new approach not only makes our code cleaner but also keeps all our redirect logic in one place. It's a pretty neat improvement, right?

While we've covered the new approach to customizing auth middlewares in Laravel 11, it's worth noting that there are many other middleware customizations available like replacing a default middleware with a custom one, adding/removing middleware to a route group, or even excluding routes from CSRF protection.

Last updated 2 weeks ago.

driesvints liked this article

1
Like this article? Let the author know and give them a clap!

Other articles you might like

November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.