14

I have a controller function like this

public function show(NovelRequest $request, Novel $novel)
{
    // load the chapters
    $novel->chapters;

    // return the detail view of a novel
    return view('novels.show', compact('novel'));
}

I receive a novel object because i m using route model binding. However, I'd like to load more than the chapters. Since it would cause many request if i now do something like

$novel->chapters;
$novel->bookmarks;
...

I wondered if theres a way to load "multiple" relations when i already have the novel object. Usually i would to something like

Novel::with('chapters', 'bookmarks')-> ...

However, I already have the novel object so i would like to not look it up a second time.

Frnak
  • 6,601
  • 5
  • 34
  • 67

2 Answers2

39

There is “Lazy Eager Loading“. The syntax is $novel->load('chapters', 'bookmarks');

Gordon Freeman
  • 3,260
  • 1
  • 22
  • 42
6

We can eager load the needed relations by customizing the resolution logic (for route model binding) by defining a resolveRouteBinding method on the model.

// In the Novel model
public function resolveRouteBinding($value)
{
    return $this->with(['chapters', 'bookmarks'])->where($this->getRouteKeyName(), $value)->firstOrFail();
}

https://laravel.com/docs/6.x/routing#explicit-binding

Abdrhmn
  • 611
  • 7
  • 6
  • 1
    that's also a good solution, however it would always load the chapters & bookmarks and not only in the context where I actually need them – Frnak Dec 16 '19 at 08:52