2

Although a similar question is asked but in a different context here. Laravel Eloquent with and find

Issue I am having right now is that when I use "find", it returns the object and not the collection.

MyModel::find($myId)

But when I use "with" it returns me the collection. Shouldn't be a single object with eager loading all the required data ?

MyModel::find($myId)->with('notes')

I am expecting it to return a single object with eager loading the notes. But its returning the collection. So I have to get the first object of the collection and then the eager loaded notes in it. But when I do something like

MyModel::find($myId)->with('notes')->first()

It returns the single object, which is correct, but doesn't make sense to me as I have read on laracast forum that "first" behind the scene uses "find". So do I really need to use "find" and "first" together to get the required data or is there something I am doing wrong ?

P.S I am using Laravel 5.3

Community
  • 1
  • 1
Abdul Mannan
  • 170
  • 1
  • 8

1 Answers1

2

Use it this way to get an object with collection:

MyModel::with('notes')->find($myId);

https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

And this should just return query builder instance:

MyModel::find($myId)->with('notes')
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • 1
    Yup, It did work. The one I posted is what I saw in one of the laracast videos but it was not using "with". Thanks for the correction. – Abdul Mannan Dec 13 '16 at 10:52