Files
besttechfrom.eu/app/Http/Controllers/UpvoteController.php
T

66 lines
1.6 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
{
/**
* Display the user's upvoted products.
*/
public function index()
{
$user = Auth::user();
$upvotes = $user->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,
]);
}
}