LoginSignup
0
0

ログイン後ページ直行を実装【Laravel】

Posted at

はじめに

未ログインの状態で、ログイン後のページのURLを踏むと、ログイン後にトップページに遷移するようになってしまっていたため、ログイン後に該当のページに遷移するように実装いたしました。

実装したコード

App/Http/Controllers/Auth/LoginController.php
    public function showLoginForm()
    {
        if (empty(session('url.intended'))) { // この部分を追加
            session(['url.intended' => route('index')]);
        }
        return view('auth.login');
    }
App/Http/Middleware/Authenticate.php
   protected function redirectTo($request)
    {
        if(!$request->expectsJson()) {
            $check = false;
            $url = url()->current();
            $whiteList = [
                // 名前付きルートを記述
            ];
            
            // ルートが存在しているかどうか確認
            foreach($whiteList as $targetname){
                $routeURL = route($targetname);
                $exists = mb_strpos($url,$routeURL);
                if($exists !== false){
                    $check = true;
                    break;
                }
            }

            // ルートが存在しており、ホワイトリスト内のルートであれば、ログイン後ページ直行
            if($check){
                session(['url.intended' => url()->current()]);
            }else{
                session(['url.intended' => route('index')]);
            }

            return route('login');
        }
    }
0
0
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
0
0