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, 希望有人能帮助我解决一下这个问题,谢谢!

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 2

应该是传入的$id有问题,我目前还没有找到具体原因

7年前 评论

我改成post方法就成功了...对PUT还是了解不太深,要研究研究为什么PUT不行...

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!