How to get correct count for like or dislike

Hi, I tried to make like/dislike in the site and I found the code in github it works but when I click like or dislike button I get 2 and not 1(exemple like:2 dislike:0) but I need like:1 dislike:0 or like:0 dislike:1 and also I get 2 message with sweetalert if I have like:1 and I click in like button to unlike product it should give me one message “you have unliked the product” and not “you have unliked the product” then " you have liked the product" so please how to change code to work correctly and thank you very much
productcontroller:

 public function jquery()
    {
        $products = Product::withCount('likes', 'dislikes')
            ->when(auth()->check(), function ($query) {
                $query->with(['ratings' => function ($query) {
                    $query->where('user_id', auth()->id());
                }]);
            })
            ->get();

        return view('site.pages.jquery', compact('products'));
    }
 public function rateProduct(Request $request)
    {
        if (auth()->guest()) {
            return response(['message' => 'You are not logged in. Please log in to rate post'], 401);
        }

        $request->validate([
            'type'    => 'required|in:like,dislike',
            'product_id' => 'required|exists:products,id'
        ]);

        $user = auth()->id();
        $product = Product::find($request->input('product_id'));

        $unrated  = (boolean) $product->ratings()->where('user_id', $user)->where('type', $request->input('type'))->count();
        $detached = (boolean) $product->ratings()->detach($user);
        if (!$unrated) {
            $product->ratings()->attach($user, [
                'type' => $request->input('type')
            ]);
        }

        $product->loadCount('likes', 'dislikes');
        $likes    = $product->likes_count;
        $dislikes = $product->dislikes_count;

        return response(compact('detached', 'unrated', 'likes', 'dislikes'));
    }

jquery.blade.php

 <div class="likes text-right" data-product-id="{{ $product->id }}">
   <a href="#" class="like{{ auth()->check() && $product->ratings->where('pivot.type', 'like')->count() ? ' active' : '' }}">
  <i class="fa fa-thumbs-up"></i> <span class="count">{{ $product->likes_count }}</span>
                                    </a>
   <a href="#" class="dislike{{ auth()->check() && $product->ratings->where('pivot.type', 'dislike')->count() ? ' active' : '' }}">
     <i class="fa fa-thumbs-down"></i> <span class="count">{{ $product->dislikes_count }}</span>
       </a>
     </div>
 </div>
@push('scripts')
   
   
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script>
$(function() {
    $('.likes a').click(function (e) {
        var _token   = $('meta[name="csrf-token"]').attr('content');
        var type     = $(this).hasClass('like') ? 'like' : 'dislike';
        var product_id  = $(this).parent('.likes').data('product-id');
        var $parent  = $(this).parent('.likes');
        $.post("{{ route('products.rateProduct') }}", {
                _token,
                type,
                product_id
            })
            .done((data) => {
                var message = 'You have ' + type + 'd this post';
                $parent.children('a').removeClass('active');
                $parent.find('.like .count').text(data.likes);
                $parent.find('.dislike .count').text(data.dislikes);
                if (data.detached && data.unrated) {
                    message = 'You have un' + type + 'd this post'
                } else if (!data.detached && !data.unrated) {
                    $(this).addClass('active');
                } else if (data.detached && !data.unrated) {
                    $(this).addClass('active');
                }
                Swal.fire(
                    'Success!',
                    message,
                    'success'
                );
            })
            .fail(({responseJSON}) => {
                var message = responseJSON.errors && responseJSON.errors[Object.keys(responseJSON.errors)[0]] ?
                    responseJSON.errors[Object.keys(responseJSON.errors)[0]][0] :
                    responseJSON.message;
                Swal.fire(
                    'Error!',
                    message,
                    'error'
                );
            });
    });
})
</script>
@endpush

I can’t spot an error in that code … Are you accidentally double clicking maybe? :thinking:

Thank you very very much @rpkamp
No I clicked just one time and I tried to follow the code correctly but I don’t know why I get 2 and not 1 what I have to do and thank you very much

Could you maybe zip up all your code or put it on GitHub or something so I can run it locally? With what you’ve provided so far I’m not able to solve this.

1 Like

i dont see where the code increments a value?

whats $detached for? (If the idea is to remove a previous like/dislike before adding the new one, why are we checking the state of $unrated? Why does detached retrieve and receive a boolean?)

Thank you @rpkamp very much
I removed the code and rewrite it from the beginning and now it works and i can’t tell you why I get the error, I decided to rewrite the code and see if I get the same error or not but it works now so thank you very very much and sorry

thank you very much @m_hutley
if you click like button you will get 1 like and when you have 1 like and you click like button you will get 0 like and if you have 1 like and click dislike button you will get 1 dislike and 0 like
and the same for dislike

Here :slightly_smiling_face:

This code creates a new rating entry in the database