Beispiel #1
0
function ajax_vote_comment()
{
    if (Auth::guest()) {
        exit;
    }
    $comment_id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    $type = isset($_POST['type']) ? (int) $_POST['type'] : 0;
    $user_id = Auth::user()->id;
    if (!($comment = Comment::find($comment_id))) {
        json_message(trans('comments.404'), false);
    }
    $vote = CommentVote::where('comment_id', $comment_id)->where('user_id', $user_id)->first();
    // Remove upvote / downvote
    if ($type == 1 || $type == 2) {
        if ($vote) {
            if ($type == 1) {
                $comment->upvotes = absint($comment->upvotes - 1);
            } else {
                $comment->downvotes = absint($comment->downvotes - 1);
            }
            $vote->delete();
        }
    } elseif ($type == 3 || $type == 4) {
        if ($type == 3) {
            $comment->upvotes = $comment->upvotes + 1;
        } else {
            $comment->downvotes = $comment->downvotes + 1;
        }
        if ($vote) {
            if ($type == 3) {
                $comment->downvotes = absint($comment->downvotes - 1);
            } else {
                $comment->upvotes = absint($comment->upvotes - 1);
            }
            $vote->type = $type == 3 ? 1 : 2;
            $vote->save();
        } else {
            $type = $type == 3 ? 1 : 2;
            CommentVote::insert(compact('type', 'comment_id', 'user_id'));
        }
    } else {
        json_message('Invalid vote type.', false);
    }
    $comment->save();
    json_message(true);
}