$categories = Category::all();
foreach($categories as $category):
$posts[] = $category->posts()->latetest()->take(10)->get();
endforeach;
I think this is fine
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to fetch 10 posts per category from database .
this code take 10 posts for all categories not for each category :
Category::with(['posts' => function($q){
$q->latest()->with('files')->take(10);
}])->get();
what is the solution ?
Here's one article on the way to do it with less server effort
https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/
but as you will see, its not a trivial problem.
Please or to participate in this conversation.