Laravel 5.3 实现文章喜欢功能有问题
今天想给我的blog添加文章喜欢的功能,我使用的mysql,为此我关联了一张外键表Vote,column为user, articleId,isLove,isUnLove
, 所以我在template里这样写的:
<a href="/articles/love/{{ $article->id }}/{{ $article->username }}" onclick="event.preventDefault();
document.getElementById('love-form').submit();">
<span class="label label-danger pull-right">
<i class="fa fa-heart-o" aria-hidden="true"></i>{{ $article->love }}
</span>
</a>
<form id="love-form" action="/articles/love/{{ $article->id }}/{{ $article->username }}" method="POST" style="display: none;">
{{ csrf_field() }}
{{ method_field('PUT') }}
</form>
这是我的route:
Route::put('/articles/love/{id}/{user}', 'ArticleController@love');
Route::put('/articles/unLove/{id}/{user}', 'ArticleController@unLove');
我在articleController的love:
public function love(Request $request, $id, $user)
{
$article = Article::findOrFail($id);
if ($vote = Vote::where('articleId', $id)
->where('user', $user)
->first()) {
if ($vote->isLove == 1) {
$request->session()->flash('error','remove love it');
Vote::where('user', $user)
->where('articleId', $id)
->update(['isLove' => 0]);
$article->love -= 1;
$article->save();
} else {
Vote::where('user', $user)
->where('articleId', $id)
->update(['isLove' => 1]);
$article->love += 1;
$article->save();
}
} else {
$vote = Vote::firstOrCreate([
'user' => $user,
'articleId' => $id,
'isLove' => 1,
'isUnLove' => 0,
]);
$article->love += 1;
$article->save();
}
return redirect('/articles');
}
当我实现完这些的时候,我发现喜欢文章功能是可以使用的,但是只能给最近发布的文章喜欢,就是哪怕在别的文章上点击喜欢,都会在最新发布的文章上操作,我用了文章分页foreach出了每个文章.
令我十分不解的是,我传入的$id指定了是哪篇文章的,可是用findOrFail出来的都是最新发布的那一篇文章,这是为什么啊?
新人初入laravel, 希望有人能帮助我解决一下这个问题,谢谢!
推荐文章: