【问题标题】:Redirect to other route when session has expired in Laravel 5.8在 Laravel 5.8 中会话过期时重定向到其他路由
【发布时间】:2021-05-09 19:17:35
【问题描述】:

我正在尝试返回另一条路线,因为在我的情况下登录它是一个模式页面,并且当会话过期时,返回此路线但它不存在。我不知道该怎么做。

我可以在网上看到这个:if(Auth::check()){ return route('/')},但我不知道我把这段代码放在哪里。

我也可以看到这个:在 'App\Exception\Handler' 中放这个:

if ($exception instanceof AuthenticationException) {
            return redirect('/');
        }

我该怎么做?

谢谢你帮助我

【问题讨论】:

标签: php laravel redirect logout laravel-5.8


【解决方案1】:

Laravel 可能已经有了你需要的东西。看看App\Http\Middleware\Authenticate 类。这是一个中间件,如果会话已过期,它将将用户重定向到“登录”命名路由(默认情况下)。 默认情况下,您放入 routes/web.php 的所有路由都不受此中间件保护,但您可以更改此设置。

方法一:在控制器的构造函数中添加auth中间件:

public function __construct()
{
    $this->middleware('auth');
}

方法 2:为您的一条路由添加 auth 中间件:

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

方法3:将所有受保护的路由添加到组中:

Route::group(['middleware' => ['auth']], function () {
    // All your protected routes go here
});

然后您可以轻松更改将用于重定向会话过期(未经过身份验证)的用户的 URL。只需编辑 App\Http\Middleware\Authenticate::redirectTo() 方法并返回您的 URL,例如:

protected function redirectTo($request)
{
    if (! $request->expectsJson()) {
        return route('yourLoginRouteName');
    }
}

【讨论】:

    【解决方案2】:

    您可以创建一个路由来检查会话,它会每分钟检查会话是否存在。 你可以这样使用:

    刀刃部分:

    @if (Auth::user())
      <script>
        $(function() {
          setInterval(function checkSession() {
            $.get('/is-logged-in', function(data) {
              // if session was expired
              if (!data.isLoggedIn) {
                // redirect to login page    
                // or, may be better, just reload page
                location.reload();
              }
            });
          }, 60000); // You can change it
        });
      </script>
    @endif
    

    路线:

    Route::get('is-logged-in', 'Auth\AuthController@checkSession');
    

    控制器:

    public function checkSession()
    {
        return Response::json(['isLoggedIn' => Auth::check()]);
    }
    

    【讨论】:

    • 感谢您的回复,但是,我需要更改默认值 laravel session expired
    猜你喜欢
    • 2018-05-12
    • 2020-08-16
    • 2019-12-31
    • 2016-05-27
    • 2020-02-13
    • 2017-12-27
    • 1970-01-01
    • 2015-06-16
    • 2019-10-26
    相关资源
    最近更新 更多