LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel】マルチログインで認証ミドルウェアのリダイレクト先をGuard(認証)別で指定する

Posted at

環境

  • PHP 8.0.3
  • Laravel 8.79.0

今回実現したい事

  • ルーティングでmiddleware auth:〇〇を使ってログインしていないユーザはGuard(認証)別のログインページにリダイレクトしたい
  • redirectToをオーバーライドしただけではGurardが分からないためGuard別のリダイレクトが出来ない

結論

AuthenticateクラスのunauthenticatedをオーバーライドしてredirectToメソッドの第二引数に$guardsを追加して使う。下記のようにすることでredirectToでguardが分かるようになる。

Authenticate.php
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Auth\AuthenticationException;

class Authenticate extends Middleware
{
    protected function unauthenticated($request, array $guards)
    {
        throw new AuthenticationException(
            'Unauthenticated.', $guards, $this->redirectTo($request, $guards) // $guardsを第二引数に追加
        );
    }

    protected function redirectTo($request, $guards) // $guardsを第二引数に追加
    {
        if (! $request->expectsJson()) {
            // middlewareがauth:adminならroute('admin.login.form')にリダイレクトされる
            if(in_array('admin', $guards)) {
                return route('admin.login.form');
            }
            
            // middlewareがauth:userならroute('user.login.form')にリダイレクトされる
            if(in_array('user', $guards)) {
                return route('user.login.form');
            }
        }
    }
}
1
0
1

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
1
0