2

I'm trying to use Laravel Eager Loading in my project and I have read the documentation about it. Every example in documentation is about getting all instances of a model with Eager Loading. But is it just about getting all instance not just a single model? Consider this :

public function single(Coin $coin)
{
    $coin = $coin->with('exchanges')->get();
    return view('public.coin',compact('coin'));
}

It is a controller method which loads a single Coin using route binding and injects the instance and I'm trying to eager load relations of that coin. but when I access $coin in my blade view file I get a list of all coins. So I can't eager load an injected model instance?!

Artin GH
  • 546
  • 2
  • 10
  • 21

1 Answers1

6

You are looking for Lazy Eager Loading.

You can achieve what you want using:

public function single(Coin $coin)
{
    $coin->load('exchanges');
    return view('public.coin',compact('coin'));
}

Also, you can eager load relations when retrieving a single model like:

Coin::with('exchanges')->find($id);
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Kurt Friars
  • 3,625
  • 2
  • 16
  • 29