Laravel 4 Eager Loading "Undefined Property"

Why can't I access the property in an eagerly loaded senario?

I am trying to access the location of a photo for my model of objects. They have a lot: a lot of relationships. When I load object information using

$facilities = Facility::with('photos')->get(); 

When I try to access

 foreach($facilities as $facility) { echo $facility->photos->id; } 

I get Undefined property: Illuminate\Database\Eloquent\Collection::$id

If I echo $facilities->photos , I get.

 [{"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"}}] 

What is the best way to access any property in this array?

+6
source share
3 answers

When photos are actively loaded, you get the photos collection and to get the photo you need to iterate through the photos collection, for example.

 foreach($facilities as $facility) { foreach($facility->photos as $photo) { echo $photo->id; } } 

If you need only the first photo, you can get it by calling the first() method in the collection

 foreach($facilities as $facility) { $facility->photos->first()->id; } 
+18
source

What is received from the database is an array with one object. This is why foreach works. To access it the way you want, you must add the first () method, as Atrim says, you can even refuse the get () method. Only I propose to do this in the controller.

 $facilities = Facility::with('photos')->first(); {{ $facilities->location }} 
+2
source

Thanks Altim, I just hit this issue, and nested foreach is one solution. However, I will share with you guys the solution that I used at the end.

Instead of a nested foreach or even bootloader, I used Builder Builder. In my case:

 $posts = DB::table('posts') ->leftJoin('users', 'posts.user_id', '=', 'users.id') ->get(); 

This allowed me to use one foreach, and all the data is on the same level, in my case, for example, it would be something like:

 @foreach ($posts as $post) <p>{{ $post->first_name }}</p> # From users table <p>{{ $post->title }}</p> # From posts table <p>{{ $post->body }}</p> @endforeach 

Perhaps he does not answer this question exactly, but I hope that he will help others, such as myself, who turned out to be in this particular question.

0
source

Source: https://habr.com/ru/post/949828/


All Articles