Skip to content
Advertisement

Get all products where average rating is equal to 5 in laravel

I have 2 Tables Products and Reviews

  • Products hasMany reviews
  • Reviews belongsTo Product

I want to get only those product which have avg(‘ratings’) is equal to 5

from controller, I get products = Product::with('category')->with('reviews')->get();

now want show in blade in one part of Top Rated Products

$product->reviews()->avg('ratings') I used this to get average ratings for a single Product.

Now I want to get a collection of products which has average rating = 5. I tried this line

$products->reviews()->avg('ratings')->where('ratings',5)->take(3)

but this not worked. Can anyone please help me with my problems?

Advertisement

Answer

You may want to try something like that:

$products = Product::with(['category', 'review'])
    ->leftJoin('reviews', 'reviews.product_id', '=', 'proucts.id')
    ->select(['products.*',
        DB::raw('AVG(reviews.rating) as ratings_average')
        ])
    ->where('ratings_average', 5)
    ->get();

You might want to experiment a bit with the syntax as I’m not quite sure that will work, but you should get the idea of what we’re trying to do.

EDIT

In case you already have your collection as $products = Product::with('category')->with('reviews')->get();, then you can even simplier filter it using:

$productsFiltered = $products->filter(function($product){
    return $product->reviews->avg('rating') == 5;
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement