根据知乎系列视频中的对答案点赞功能,做了下例子。是一个vue写的组件。结果出错了Call to a member function hasVotedFor() on null
。测试后,发现model中的VoteFor也是同样的错误。去google了类似问题,觉得没有找到答案。不清楚该如何解决此问题。若能得到帮助,不胜感激。
下面是Votecontroller:
public function users($id)
{
$user = Auth::guard('api')->user();
if($user->hasVotedFor($id)){
return response()->json(['voted' => true]);
}
return response()->json(['voted' => false]);
}
public function vote()
{
$answer = $this->answer->byId(request('answer'));
$voted = Auth::guard('api')->user()->voteFor(request('answer'));
if (count($voted['attached'])>0){
$answer->increment('votes_count');
return response()->json(['voted' => true]);
}
$answer->decrement('votes_count');
return response()->json(['voted' => false]);
}
UserModel:
public function votes()
{
return $this->belongsToMany(Answer::class,'votes')->withTimestamps();
}
public function voteFor($answer)
{
return $this->votes()->toggle($answer);
}
public function hasVotedFor($answer)
{
return !! $this->votes()->where('answer_id',$answer)->count();
}
Route:
Route::post('answer/{id}/votes/users','VoteController@users')->middleware('api');
Route::post('answer/vote','VoteController@vote')->middleware('api');
UserVoteButton.vue:
<template>
<button
class="btn btn-default"
v-bind:class="{'btn-primary': voted}"
v-text="text"
v-on:click="vote"
></button>
</template>
<script>
export default {
props:['answer','count'],
mounted() {
this.$http.post('http://localhost:8000/api/answer/' + this.answer + '/votes/users').then(response =>{
this.voted = response.data.voted
})
},
data(){
return {
voted:false
}
},
computed:{
text(){
return this.count
}
},
methods: {
vote(){
this.$http.post('http://localhost:8000/api/answer/vote', {'answer':this.answer}).then(response => {
this.voted = response.data.voted;
response.data.voted ? this.count ++ : this.count --
})
}
}
}
</script>