LoginSignup
34
18

More than 5 years have passed since last update.

【Laravel】middleware authのリダイレクト先を変更する【Route [login] not defined.】

Posted at

今回困ったこと

  • ルーティングでmiddleware authでログインしているユーザーのみ閲覧できるように制限した
  • ログインしていない状態でそのページにアクセスした時、デフォルトの挙動だと[login]というルート名にリダイレクトしようとする。
  • ルート名を[login]以外にしたいとき(挙動を変更したい時)にどうすれば良いか。

具体的には以下のようなエラー


InvalidArgumentException
Route [login] not defined.
-----------------------------------------------
    public function route($name, $parameters = [], $absolute = true)
    {
        if (! is_null($route = $this->routes->getByName($name))) {
            return $this->toRoute($route, $parameters, $absolute);
        }

        throw new InvalidArgumentException("Route [{$name}] not defined.");
    }

結論

app/Exceptions/Handler.phpで、 Illuminate\Auth\AuthenticationExceptionをインポート(use)して、Handlerクラスのunauthenticatedをオーバーライドする

app/Exceptions/Handler.php
use Illuminate\Auth\AuthenticationException;

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest(route('login')); // ここを変更する
    }

middleware authってなにをしてるんだろう??

  • ログイン状態のチェックを行なっているようだ
  • OKなら、return $next($request);
  • NGなら、Unauthenticatedという例外を投げているようだ
  • 例外は、Illuminate/Foundation/Exceptions/Handler.phpでキャッチされて、function unauthenticatedで処理されているようだ

(Illuminate\Auth\Middleware\Authenticateの中で定義されているようなので、詳しくはそちらを覗いてみてください…!)

34
18
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
34
18