首页 文章

Laravel - 无法在Exception Handler.php文件的渲染功能中访问Sessions

提问于
浏览
1

说是404异常处理我试图根据用户会话分别为管理页面和首页显示404页面,以下是我的Handler.php文件的渲染功能

public function render($request, Exception $e)
{
    echo Session::has('user.id');
    ...
    ...
}

Session::has('user.id') 总是返回空值,我无法确定用户是否实际登录 .

在我的一个旧的Laravel项目中,我使用了相同的逻辑并且成功运行,目前的项目Laravel版本是 5.2.45

谢谢您的帮助 .

2 回答

  • 0

    您将遇到的问题是 StartSession 中间件尚未运行的404错误,因此从技术上讲,抛出异常时用户信息尚不可用 .

    一种解决方案可能是专门检查 endpoints ,例如包含管理关键字 /admin/doesnotexist 的内容,但它是否有限,就好像您尝试只是 /testing 目的不明确,用户是否请求前端或后端资源?

    另一种选择是:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof NotFoundHttpException) {
            return redirect('/displaynotfound');
        }
        return parent::render($request, $exception);
    }
    
    Route::get('/displaynotfound', function() {
        // Do what you need todo, as you will have access to
        // to the user.
        dd(auth()->user());
    });
    
  • 0

    我建议使用 auth() -helper或 Auth -Facade来检索有关当前登录用户的信息,并检查用户是否已登录 .

    用户ID

    auth()->id();
    Auth::id();
    

    检查用户是否已登录

    auth()->check();
    Auth::check();
    

    https://laravel.com/docs/5.5/authentication#retrieving-the-authenticated-user

相关问题