Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Eager Loading "Undefined Property"

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?

like image 302
Jared Meyering Avatar asked Jul 19 '13 14:07

Jared Meyering


2 Answers

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;
}
like image 52
Altrim Avatar answered Oct 23 '22 15:10

Altrim


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 }}
like image 24
sidneydobber Avatar answered Oct 23 '22 17:10

sidneydobber