Laravel 5.5试图获得非对象的属性

时间:2017-10-09 13:29:30

标签: php laravel

public function __construct()
{
    view()->share('tags', DB::table('tags')->where('view', Auth::user()->view)->get());
    $this->middleware('auth');
}

我收到:

  

(1/1)ErrorException   试图获得非对象的属性

为什么呢?当我尝试return Auth::user()->view;时,我得到 2 。但是当我手动输入->where('view', 2)时,一切正常。我怎样才能解决这个问题?提前谢谢。

2 个答案:

答案 0 :(得分:1)

你在 Auth :: user() - >查看之后使用了auth中间件,这是错误的

public function __construct()
{
    $this->middleware('auth'); // firstly auth check , after that can use Auth::user() , before them Auth::user() return null   and you cant use ->view on null , when ErrorException Trying to get property of non-object
    view()->share('tags', DB::table('tags')->where('view', Auth::user()->view)->get());
}

您的用户未签名请检查

  

验证::校验()

然后使用

  

验证::用户() - >查看

答案 1 :(得分:1)

尝试返回gettype (Auth::user()->views)以查看其是否为整数。如果不只是(int)Auth::user()->views来制作它。

或尝试将其分配给这样的变量:

$views = (int)(Auth::user()->views);

然后使用它...... ->where('view', $views)->get());