Laravel 实战开发知乎:用户关注问题 Part 2
打赏作者

yurenzhen

老师,为什么我没有查到toggle这个方法?

JellyBool 回复 yurenzhen

这个是 5.3 之后的版本才有的

weir2009

用户登陆的时候,功能都是正常的。但退出登陆之后,访问问题页面就会报错,这个问题要怎么解决呢:
ErrorException in da970cb938287b918147b2d72063f5c4456aeb18.php line 44:
Call to a member function followed() on null (View: D:\laragon\www\l53-zhihu\resources\views\question\show.blade.php)

<a href="/question/{$question->id}/follow" 
                    class="btn btn-default {Auth::user()->followed($question->id) ? 'btn-success' : ''}">
                    {Auth::user()->followed($question->id) ? '已关注' : '关注该问题'}</a>
JellyBool 回复 weir2009

你判断一下先呗 :

@if(Auth::check()) 
weir2009 回复 JellyBool

嗯,刚才自己解决了。

@if (Auth::check())
                        <a href="/question/{$question->id}/follow" 
                        class="btn btn-default {Auth::user()->followed($question->id) ? 'btn-success' : ''}">
                        {Auth::user()->followed($question->id) ? '已关注' : '关注该问题'}</a>
                    @else
                        <a href="/login" class="btn btn-default">关注问题</a>
                    @endif

这么简单的问题,不该问老师。

JellyBool 回复 weir2009

嗯哼,对的。就是这个样子

liujun 回复 weir2009

可以用optional辅助函数,亲测有效

Yanniyiyi

toggle()方法返回一个数组,通过查看返回值就可以对question的followers_count进行加减操作了。

呆呆的罗浩

mark

return !! $this->follows()->where('question_id', $question)->count(); // 强制返回bool值
m2417599488

jelly,我发现laravel中开发很多地方都是页面跳转,这样是否会导致用户体验变差呢?这么不用ajax来进行用户操作呢

JellyBool 回复 m2417599488

用不用 Ajax 不是取决于你么

m2417599488 回复 JellyBool

这个倒是,只是看到你视频中跳转用得比较多,所以有这个疑问

imcode

Missing argument 1 for App\User::follows(), called in D:\code\php\zhihu\app\User.php on line 58 and defined

//关注
public function follows($question){
    return $this->belongsToMany(Question::class,'user_question')->withTimestamps();
}

public function followThis($question){
    return $this->follows()->toggle($question);
}
imcode

解决了
public function followThis($question){
return this>follows(this->follows(question)->toggle($question);
}
这个方法应该 return this>follows(this->follows(question)->toggle($question); 这样写

liujun

判断是否关注应该也可以用collection的方法contains吧,里面传入$question

JellyBool 回复 liujun

是可以的啊,只不过视频演示了不同的方式