【问题标题】:Laravel - Unable to access Sessions in render function of Exception Handler.php fileLaravel - 无法在 Exception Handler.php 文件的渲染功能中访问会话
【发布时间】:2018-03-19 17:51:10
【问题描述】:

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

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

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

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

感谢您的帮助。

【问题讨论】:

  • 你能把传递user.id 的方法贴到会话中吗?
  • 为什么在这种情况下使用 session 并且没有忘记导入 Session?

标签: php laravel session exception-handling


【解决方案1】:

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

用户 ID

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

检查用户是否登录

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

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

【讨论】:

    【解决方案2】:

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

    一种解决方案可能是专门检查端点,例如包含管理员关键字/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());
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多