Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Laravel how to eager load find method

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();
like image 770
James Okpe George Avatar asked Jan 05 '16 16:01

James Okpe George


People also ask

How eager loading works in laravel?

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.

What does get () do in laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

What is lazy vs eager loading in laravel?

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.

What is eager loading in PHP?

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.


1 Answers

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);
}
like image 170
Thomas Kim Avatar answered Sep 19 '22 07:09

Thomas Kim