Eager Load Limit is Coming to Laravel 11

With the release of Laravel 11 in February 2024, Laravel will have native support for limiting the number of eagerly loaded results per parent.

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

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 0
select * 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` <= 3
order 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!


The post Eager Load Limit is Coming to Laravel 11 appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

Read more

© 2024 Extly, CB - All rights reserved.