9

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();
George
  • 3,757
  • 9
  • 51
  • 86

1 Answers1

16

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);
}
Thomas Kim
  • 15,326
  • 2
  • 52
  • 42
  • Thanks @ThomasKim, I really appreciate, works as I want – George Jan 05 '16 at 17:17
  • This was helpful. I was wrong to assume that `User::find(1)->with('pages');` would work the same way. – Ryan Jan 12 '19 at 18:10
  • Ahh, I find myself back here at this question again. This time it was to learn that this works (camelCased): `$contact = \App\Models\Contact::with('callFlow')->find($this->contactId);` while this does not: `$contact = \App\Models\Contact::with('call_flow')->find($this->contactId);` – Ryan Feb 04 '19 at 21:22