laravel : Call to a member function followed() on null

用户关注问题的多对多关联,查询不到数据的时候报错:

User.php

//用户关注问题,users表与quesitons表多对多关联
public function follows ()
{
   return $this->belongsToMany('App\Quesiton','user_question')->withTimestamps();
}

//返回用户是否关注了某个问题
public function followed($question)
{
   return $this->follows()->where('question_id', $question)->count();
}

welcome.blade.php

//在视图中显示用户是否关注了问题,
{{ Auth::user()->followed($question->id) ? '已关注':'关注' }}

当用户没有关注问题的时候,报错:

Call to a member function followed() on null

可是用dd()又能返回0或1:

TestController.php

public function isFollowedOrNot($question)
{
   dd(Auth::user()->followed($question));  //0
}
阅读 3.6k
1 个回答

那个报错说的是在你 {{ Auth::user()->followed($question->id) ? '已关注':'关注' }} 这个用的时候,Auth::user()null, 可以想象你这个问题出现应该是在用户没有登录的时候发生的。

外面包裹一个Auth::check() 判断吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进