Why can't I access the property in an eager loaded senario?
I am trying to access the photo location for my facilities model. They have a Many:Many relationship. When I load the facility info using
$facilities = Facility::with('photos')->get();
When I try to access
foreach($facilities as $facility)
{
echo $facility->photos->id;
}
I get the Undefined property: Illuminate\Database\Eloquent\Collection::$id
If I echo $facilities->photos
I end up with.
[{"id":"3",
"name":null,
"location":"facilities\/facility1.jpg\r",
"created_at":"2013-07-18 14:15:19",
"deleted_at":null,
"updated_at":null,
"pivot":{"facility_id":"5","photo_id":"3"}}]
Whats the best way to access any property in this array?
With eager loading the photos
you get a photos
collection and in order to get the photo you need to iterate through the photos
collection e.g.
foreach($facilities as $facility)
{
foreach($facility->photos as $photo)
{
echo $photo->id;
}
}
If you only want just the first photo you can get it by calling the first()
method on the collection
foreach($facilities as $facility)
{
$facility->photos->first()->id;
}
What is received from the database is an array with one object. This is why a foreach works. To access it the way you want you should add the first() method just as Atrim says, you can even drop the get() method. Only I would suggest doing it in the controller.
$facilities = Facility::with('photos')->first();
{{ $facilities->location }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With