SmokeTM
164
6
Laravel

Save votes of a model in database

Posted 7 months ago by SmokeTM

I wanna save my article votes in to database, but I am not able to do so. Here is my code which doesn't work properly.

    public function store(Article $article, Request $request)
    {

        if(Gate::denies('vote', $article)) {
          abort(403, 'This action is unauthorized.');
        }

        $user = auth()->user();

        $voted = $user->votedFor($article);

        if($voted) {
          $user->unvoteFor($article);
        } else {
          $user->voteFor($article);
        }

        /* Update votes */
        $article->article_votes = $article->votes->count();
        $article->save();
        /* Set article to active if there are enough votes.
        *   Means Article will be displayed on the front page.
        */
        $article->setActive();

        return response()->json(['success' => true, 'count' => $article->fresh()->votes->count(), 'voted' => $voted]);
    }

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.