I have a model Users
which has-many Pages
, I want to eager load the method below so that it returns only a single user with all the pages eager loaded, how do I go about it.
$user = User::find(1);
$pages = $user->pages();
foreach($pages as $page) {
var_dump($page->name);
}
What I tried but doesnt work, it loads everything instead:
$user = User::with('Pages')->get();
$pages = $user->pages();
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
Lazy Loading vs. Eager Loading. While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
Eager loading is a concept in which when retrieving items, you get all the needed items together with all (or most) related items at the same time. This is in contrast to lazy loading where you only get one item at one go and then retrieve related items only when needed.
Drop the parenthesis.
$user = User::find(1);
$pages = $user->pages;
foreach($pages as $page) {
var_dump($page->name);
}
If you want to eager load it, then use the with
method and pass the correct parameter, which would be the name of your relationship methods:
$user = User::with('pages')->find(1);
foreach($user->pages as $page) {
var_dump($page->name);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With