もがき系プログラマの日常

もがき系エンジニアの勉強したこと、日常のこと、気になっている技術、備忘録などを紹介するブログです。

laravelのRedirectorのintendedメソッド

はじめに

こんばんは。

何気なく使ってた intended メソッドですが、ふわっと使ってたので、きちんとドキュメントよんでみました。

本題

readouble.com

Laravelのリダイレクタが提供するintendedメソッドは、認証ミドルウェアによってインターセプトされる前に、アクセスしようとしたURLへユーザーをリダイレクトします。目的の行き先が使用できない場合のために、このメソッドにはフォールバックURIが指定できます。

実際のメソッドはこちら

    /**
     * Create a new redirect response to the previously intended location.
     *
     * @param  mixed  $default
     * @param  int  $status
     * @param  array  $headers
     * @param  bool|null  $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function intended($default = '/', $status = 302, $headers = [], $secure = null)
    {
        $path = $this->session->pull('url.intended', $default);

        return $this->to($path, $status, $headers, $secure);
    }

事前にセッションに保存している行き先へ飛ばそうとしているみたいです。

このセッションを保存してる場所は同クラス内の guest() メソッドでした。

    /**
     * Create a new redirect response, while putting the current URL in the session.
     *
     * @param  string  $path
     * @param  int  $status
     * @param  array  $headers
     * @param  bool|null  $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function guest($path, $status = 302, $headers = [], $secure = null)
    {
        $request = $this->generator->getRequest();

        $intended = $request->isMethod('GET') && $request->route() && ! $request->expectsJson()
                        ? $this->generator->full()
                        : $this->generator->previous();

        if ($intended) {
            $this->setIntendedUrl($intended);
        }

        return $this->to($path, $status, $headers, $secure);
    }

guest() 自体はどこで呼ばれているかというと

ExceptionHandler クラス内で AuthenticationException が発生した際に実行される

unauthenticated() で呼ばれてます。

    /**
     * Convert an authentication exception into a response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $this->shouldReturnJson($request, $exception)
                    ? response()->json(['message' => $exception->getMessage()], 401)
                    : redirect()->guest($exception->redirectTo() ?? route('login'));
    }

終わりに

以前全部のredirectで intended() を指定してたプロジェクトがあったので、使い方間違えてたんだなぁと思いました。

現場からは以上です。

おまけ

なんとか読書グセをつけようと、現在読んでいるのはこちら

1日2ページとか10分だけとか

毎日少しだけでもいいからと思いながら、頑張って読んでいます。