Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahzadbuckstec's avatar

Selecting n rows from products for each category

I want to show product listing (8 products) for only 7 categories ids, I used whereIn condition but it displays only one category products that is not good.

I know if I run 7 queries and then merge the results in one array then it is possible but can someone have a better idea how to display products from different categories in one query or eloquent model.

$luxuryProductsCategoriesIds = [2495,2508,2573,2598,2625,2635,3189];
$specialLuxuryListings = Product::where('status', 1)
            ->where('price','>=',200)
            ->whereIn('exact_cat_id',$luxuryProductsCategoriesIds)
            ->inRandomOrder()
            ->limit(8)
            ->get();
0 likes
8 replies
staudenmeir's avatar

Thanks, @snapey.

Yes, you can achieve this with my package:

$luxuryProductsCategoriesIds = [2495,2508,2573,2598,2625,2635,3189];
$specialLuxuryListings = Product::where('status', 1)
    ->where('price','>=',200)
    ->whereIn('exact_cat_id',$luxuryProductsCategoriesIds)
    ->inRandomOrder()
    ->groupLimit(8, 'exact_cat_id')
    ->get();

To make this work, you have to use the HasEagerLimit in your model:

class Product extends Model
{
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
3 likes
Towoju5's avatar

This is a late response but i believe it might be useful in the future to someone.. Just had the same issue and this how I solved mine.

$cat_based = Category::where('status', 1)->with('products')->inRandomOrder()->get();

@foreach ($cat_based as $category)
	  @foreach($category->products->take(8) as $cat)
			{{$cat->name}}
      @endforeach
@endforeach
frankielee's avatar

@Towoju5

You can do this instead

Category::where('status', 1)->with(['products'=>function($q){
		$q->take(8);
}])->get();;
Snapey's avatar

@frankielee no, this will not work, for the same reason as the original question

@towoju5 loading all products into memory is a stupid idea

Please or to participate in this conversation.