With the release of Laravel 11 in February 2024, Laravel will have native support for limiting the number of eagerly loaded results per parent.
We've integrated the code behind @staudenmeir's "eager load limit" package into Laravel 11.
— Taylor Otwell (@taylorotwell) January 16, 2024
That means in Laravel 11 this will actually work... retrieving users while eager loading only 5 posts per user... ❤️
Thanks @staudenmeir! pic.twitter.com/4IAbefwVJP
Let’s say, for example, that you want to paginate users but also eagerly load three blog posts for each user:
User::with([ 'posts' => fn ($query) => $query->limit(3)])->paginate();
The above eloquent query would look something like the following JSON representation out of the box, with optimized eager-loaded models:
Using Laravel 10 or less, it is still conveniently possible via Jonas Staudenmeir’s eager-load-limit, but will now be natively supported out of the box with Laravel 11. Here’s an example of what queries you can expect in Laravel 11 for the above code:
select count(*) as aggregate from `users`select * from `users` limit 15 offset 0select * from ( select *, row_number() over (partition by `posts`.`user_id`) as `laravel_row` from `posts` where `posts`.`user_id` in (1, 2, 3...))as `laravel_table` where `laravel_row` <= 3order by `laravel_row`
The integration for Laravel 11 was done in Pull Request #49695. A massive shout-out to Jonas for incorporating this much-used package into the core of Laravel!