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

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 2

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

8年前 评论

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

8年前 评论