I'm trying to build a product rating system in Laravel. I have two different tables product
and review
where all products and reviews data are stored.
product
Table has fields like id, name, price, etc.
review
table has fields like id, product_id, rating, etc.
One product can have many reviews/ratings. I need to fetch all products with each product's average rating and total rating. I can fetch all products like the below:
$product = Product::all();
but how can I get average rating and total rating(count) also for each and every product? Every answer will be very helpful for me and admirable.
My Answer:
You can achieve this by using Laravel's Eloquent ORM and the `withCount()` and `withAvg()` methods. Here's an example of how you can fetch all products with their average rating and total rating:
php
$products = Product::withCount('reviews')->withAvg('reviews', 'rating')->get();
foreach ($products as $product) {
echo "Product Name: " . $product->name . "
";
echo "Average Rating: " . $product->reviews_avg_rating . "
";
echo "Total Ratings: " . $product->reviews_count . "
";
}
In the above code snippet, we are using the `withCount()` method to get the total number of reviews for each product and the `withAvg()` method to get the average rating for each product. The `reviews` in the methods refer to the relationship name defined in your `Product` model for the reviews.
This will give you a collection of products with their average rating and total rating, which you can then loop through to display the information as needed.
Rate this post
5 of 5 based on 2889 votesComments