Support the ongoing development of Laravel.io →
Database Eloquent

hi i have multiple categories and each category has many posts, i want fetch 4 last posts for each category, i use this code:

$catsWitposts= $this->categories->with(['posts' => function($query){
							$query->where('show', '=', 1);
							$query->limit(4);
							$query->orderBy('created_at', 'desc');
						}])->get();

but this code show 4 posts for all category

query result should be display:

cat-01
     post-01
     post-02
     post-03
     post-04
cat-02
     post-05
     post-06
     post-07
     post-08
cat-03
     post-09
     post-10
     post-11
     post-12
....

thank you every body :)

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

livana livana Joined 30 May 2014

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.