認証前のユーザが/admin配下ページにアクセスしてきたら/admin/loginに、/user配下ページにアクセスしてきたら/user/loginにリダイレクトさせたかった。
前提
-
config/auth.phpのguardsにusersとかadminが追加されている -
$this->middleware('auth:admin');的なコードが記述されている
Handler.phpを編集
exception->guards()[0]でアクセスしようとしたURLがなんのguardによって弾かれたかが取れる。
app/Exceptions/Handler.php
protected function unauthenticated($request, AuthenticationException $exception)
{
if($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
switch($exception->guards()[0]){
case 'user':
return redirect()->guest('user/login');
break;
case 'admin':
return redirect()->guest('admin/login');
break;
default:
return redirect('/');
break;
}
}