kensmithzzz
3 months ago
267
1
Laravel

EloquentModel::find(id)->with('relation')

Posted 3 months ago by kensmithzzz

I've been tripped up by this several times.

I'll write

$user = User::find(1)->with('some_relation')->get()

expecting to get just one record, and what I get is all the users.

Using with() creates a query builder instead, which I guess just ignores the find(id) part altogether. Am I misunderstanding something here?

I use this instead:

$user = User::where(id, 1)->with('some_relation')->get()

But it would be nice if there were an error thrown or something with the original.

I also know that I could do with() first and then find(), but that loads all the records and then keeps only one. I want a query that returns one result.

Please sign in or create an account to participate in this conversation.