InvalidSyntax
InvalidSyntax

Reputation: 9495

RedirectIfAuthenticated for custom guards in Laravel

I have a custom provider called business_user which users can be logged in as. I have set this up by adding this to my auth.php file.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'business_user' => [
        'driver' => 'session',
        'provider' => 'business_users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

I want to try and add the guest middleware to my business users login/sign up routes so they get redirected to my logged in dashboard.

I have done this by adding the guest middleware to the appropriate routes and then added this to my RedirectIfAutenticated class.

public function handle($request, Closure $next, $guard = null)
    {
        if ($guard == "business_user" && Auth::guard($guard)->check()) {
            return redirect('/business/dashboard');
        }
        if (Auth::guard($guard)->check()) {
            return redirect('/dashboard');
        }

        return $next($request);
    }

For normal users, they get redirected to /dashboard as expected, but my business_users don't get redirected to /business/dashboard, they just land on their intended page.

Can someone explain what I'm missing?

EDIT: I protect my signup/login routes like this:

Route::middleware(['guest'])->group(function () {
    Route::view('/business/sign-up', 'business.registration')->name('business.registration');
    Route::view('/business/login', 'business.login')->name('business.login');
});

Upvotes: 1

Views: 1218

Answers (1)

InvalidSyntax
InvalidSyntax

Reputation: 9495

Changing my code to as follows has got it working:

   public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard('business_user')->check()) {
            return redirect('/business/dashboard');
        }
        if (Auth::guard($guard)->check()) {
            return redirect('/dashboard');
        }

        return $next($request);
    }

Upvotes: 1

Related Questions