Search code examples
eloquenteager-loadinglaravel-7laravel-models

Laravel Eager Loading on a single injected model


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?!


Solution

  • 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);