n Laravel Eager Loading - load() Vs. with() | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Laravel Eager Loading - load() Vs. with()

 

Eager loading using with()

If we eager load using with(), for example:

$users = User::with('comments')->get();

 

if we have 5 users, the following two queries get run immediately:

select * from `users`
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)

…and we end up with a collection of models that have the comments attached to the user model, so we can do something like $users->comments->first()->body.

 

“Lazy” eager loading using load()

In this approach, we can separate the two queries, first by getting the initial result:

$users = User::all();

which runs:

select * from `users`

And later, if we decide(based on some condition) that we need the related comments for all these users, we can eager load them after the fact:

if($someCondition){
  $users = $users->load('comments');
}

 

which runs the 2nd query:

select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)

And we end up with the same result, just split into two steps. Again, we can call $users->comments->first()->body to get to the related model for any item.

 

Conclusion

When to use load() or with()?

load() gives you the option of deciding later, based on some dynamic condition, whether or not you need to run the 2nd query.

If, however, there’s no question that you’ll need to access all the related items, use with().

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook