Support the ongoing development of Laravel.io →
Database Eloquent

greetings!

so, i want to get X random models from a parent:

i have sub-categories and they have many products:

  • subcat 1: N products
  • subcat 2: N products
  • subcat 3: N products
  • etc.

i can do SubCategory::with('products')->get() and i will have a collection of subcats and their products.

however i want to get only a certain number of products per subcategory, after reading some documentation i came up with this:

$var = SubCategory::with(['products' => function($query){
  // $query(get X random products...); <- this is what i want
}])->get();

// like so:
$var = SubCategory::with(['products' => function($query){
  $query->random()->take(3);
}])->get();

// random() is just a scope.

which works except it only gets ONLY X products in the total, not per subcategory:

  • subcat 1: 3 products
  • subcat 2: 0 products
  • subcat 3: 0 products

i want:

  • subcat 1: 3 products
  • subcat 2: 3 products
  • subcat 3: 3 products

after struggling with this problem i did this solution:

$subCats  = SubCategory::all();
$productsCollection = collect();

foreach ($subCats as $cat) {
  $productsCollection->push($cat->products()->random()->take(3)->get());
}

that works as i want to, however i'm pretty sure there's a better and elegant solution.

any help/advice is much appreciated, thanks for reading!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

slayerfat slayerfat Joined 20 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.