upvotes() ->with(['product.category', 'product.user']) ->whereHas('product', function ($query) { $query->approved(); }) ->latest() ->paginate(12); return view('upvotes.index', compact('upvotes')); } /** * Toggle upvote for a product. */ public function store(Product $product): JsonResponse { $user = Auth::user(); // Check if user already upvoted $existingUpvote = Upvote::where('user_id', $user->id) ->where('product_id', $product->id) ->first(); if ($existingUpvote) { // Remove upvote $existingUpvote->delete(); $upvoted = false; } else { // Add upvote Upvote::create([ 'user_id' => $user->id, 'product_id' => $product->id, ]); $upvoted = true; } // Get fresh upvotes count $upvotesCount = $product->upvotes()->count(); return response()->json([ 'success' => true, 'upvoted' => $upvoted, 'upvotesCount' => $upvotesCount, ]); } }