The code you've provided for the RedirectIfAuthenticated middleware in Laravel 11 is almost correct, but it's missing the break statements in the switch cases. Without the break statements, the code will fall through to the next case after executing the code for a matched case. Here's the corrected version of your middleware:
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'lbenz':
if (Auth::guard($guard)->check()) {
return redirect()->route('lbenz.dashboard');
}
break; // Add this break
case 'lbenz_contacts':
if (Auth::guard($guard)->check()) {
return redirect()->route('lbenz.user.dashboard');
}
break; // Add this break
default:
if (Auth::guard($guard)->check()) {
return redirect()->route('zsc.dashboard');
}
// No need for a break here since it's the last case
}
return $next($request);
}
Make sure to import the Auth facade at the top of your middleware file if it's not already there:
use Illuminate\Support\Facades\Auth;
This middleware will now correctly redirect authenticated users based on the guard that is being used. If the guard is 'lbenz', it will redirect to the 'lbenz.dashboard' route. If the guard is 'lbenz_contacts', it will redirect to the 'lbenz.user.dashboard' route. For any other guard, it will redirect to the 'zsc.dashboard' route. If no guard is authenticated, it will simply pass the request to the next middleware in the stack.