4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelで認証前のリダイレクト先のログインページを振り分ける

Posted at

認証前のユーザが/admin配下ページにアクセスしてきたら/admin/loginに、/user配下ページにアクセスしてきたら/user/loginにリダイレクトさせたかった。

前提

  • config/auth.phpguardsusersとか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;
    }
  }
4
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?