Laravel 4 Eager Loading "Undefined Property"

laravel, laravel-4, php

Solution

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;
}

Problem

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?

Original source