Ad

PHP: Laravel How To Eager Load Find Method

- 1 answer

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();
Ad

Answer

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);
}
Ad
source: stackoverflow.com
Ad