5
7

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 3 years have passed since last update.

Laravenの認証タイムアウト時のリダイレクト先(複数のログインページ対応版)

Posted at

ログインが切れてリダイレクトされるページの設定

基本的にはマニュアルにある、Laravel 6.x 認証 > 未認証ユーザーのリダイレクトのセクションに記載されている通り。
https://readouble.com/laravel/6.x/ja/authentication.html

このサンプルでは、認証が1つのケースではこれだけで十分ですが、複数のログインを使う時は、
これだと、どのユーザーでも同じログインURLに戻されてしまいます。

URIで振り分ける

ログインページの条件によって、リダイレクト先を変更したいと思います。
やり方は、URIを使って、どのページを表示しようとしていたのか、把握して条件分岐します。
route('xxxx')は、routes/web.php で各自設定したものを使います。

app/Http/Middleware/Authenticate.phpAuthenticate.php

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            $URI = explode("/", $request->getRequestUri());
            switch ($URI[1]){
                //管理画面が https/xxx.xxx/admin/xxxxxのケース
                case 'admin':
                return route('admin_login');

                //管理画面が https/xxx.xxx/shop_admin/xxxxxのケース
                case 'shop_admin':
                return route('shop_admin_login');

                //ユーザーマイページが https/xxx.xxx/mypage/xxxxxのケース
                case 'mypage':
                return route('login');
            }
        }
    }
}



このように、どこのページを開こうとしてセッションタイムアウトになったかで、ログインページの表示を振り分けることができます。
またログインページが複数ある場合は、設定しておくと便利かと思います。

ご参考ください。

5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?