php - laravel 5.4:无法在 __construct 方法中访问 Auth::user()

标签 php laravel laravel-5.4

在以前版本的 Laravel 中,在我需要访问已登录用户的所有方法中的 Controller 中,我曾经做过这样的事情:

class DashboardController extends Controller
{
    private $user ;
    function __construct(Request $request)
    {
        $this->middleware('auth');
        $this->user = \Auth::user();
    }

    function func_1(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_2(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_3(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }

主要是因为我不喜欢默认语法 \Auth::user() 但在升级到 5.4 之后这不再起作用了,我得到了 null $this->用户

虽然在其他方法中效果很好。基本上 \Auth::user()__construct 方法中返回 null 但在其他函数中工作正常。

最佳答案

作为doc说:

In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

那么试试这个:

public function __construct()
{
    $this->middleware('auth');
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();

        return $next($request);
    });
}

关于php - laravel 5.4:无法在 __construct 方法中访问 Auth::user(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45055618/

相关文章:

javascript - 通过 JavaScript XHR2 对象在 PHP 中发送 ArrayBuffer

php - JSON 和 PHP 数组

laravel - 如何卸载 Laravel Passport

php - 在 Laravel 5.4 中将空值转换为空字符串

php - 如何在 Markdown 通知中插入换行符

php - 是否可以在 php 中实例化一个函数?

php - YouTube API:获取完整的播放列表

php - GROUP_CONCAT 给出了错误的值

php - 如何在 Laravel 5.7 中限制对数据库的数据输入

composer-php - 由于无法使用词法变量$ eventName作为参数名,Laravel CLI无法创建新应用