fabian
fabian

Reputation: 5463

Laravel eager loading issue with findOrFail()

Why to I get multiple results for this? I just want the "contacts" for the given client id. Not for all clients.

public function edit($id)
{
    $client = Client::findOrFail($id)->with('contacts')->get();
}

Thanks,

Upvotes: 2

Views: 1456

Answers (2)

Juliatzin
Juliatzin

Reputation: 19695

While Joel Hinz response is correct, you can still have eager loading in this query.

Just do:

$client = Client::with('contacts')->findOrFail($id);

Upvotes: 4

Joel Hinz
Joel Hinz

Reputation: 25384

Basically, findOrFail() finds a single result for you instead of returning a collection. What that means is that it already does a get() call for you. So you can't add another get() after that. If you do, you'll get weird results as you noticed because you're essentially building a new query.

That also means that you don't need to eager load anything. The reason eager loading is good is because it allows you to fetch data for multiple objects in a single query. But you only have one object here anyway - so it doesn't really matter.

You could easily do just $client = Client::findOrFail($id); and then $client->contacts later, when you need the contacts. It won't make your performance worse.

And if you only want the contacts, not the client, you could easily do this: $client = Client::findOrFail($id)->contacts;

Upvotes: 3

Related Questions