48 lines
1.1 KiB
PHP
48 lines
1.1 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace App\Http\Controllers;
|
||
|
|
|
||
|
|
use App\Models\Product;
|
||
|
|
use App\Models\Upvote;
|
||
|
|
use Illuminate\Http\JsonResponse;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use Illuminate\Support\Facades\Auth;
|
||
|
|
|
||
|
|
class UpvoteController extends Controller
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* 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,
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|