I get data with relations from controller but can't use in blade
Controller..
$employees = Post::where('user_id', $user_id)->with('people')->get();
Blade, I use in foreach like..
$employee->people->image
But it gives error
Property [image] does not exist on this collection instance.
When I dd($employees)
the problem is that the variable $employee (which contains model Post btw) has relation 1:N to People I assume
meaning you have to loop the people collection returned by the relation
eg
@foreach($employees as $employee)
@foreach($employee->people as $person)
{{ $person->image }}
@endforeach
@endforeach
You must foreach people relationship, you are getting collection with people for that post so you must foreach it because relationship return array with all people per post.
@foreach($employees as $employee)
@foreach($employee->people as $user)
{{ $user->image }}
@endforeach
@endforeach
If you want only one from people you could use
$employee->people->first()->image
Whin this way you should use
@if( $employee->people->first()->image)
{{ $employee->people->first()->image }}
@endif
Please check you post model does it have relation function defined?
public function people() {
return $this->hasMany(people::class); // Add localID and foreign_key ID as param if requires
}
Also check image property is there
Please check Property [title] does not exist on this collection instance hope this help
In this case, each post has a lot of people. So, you need to specify from which people you want to get the information. For example, this code can be work:
$employee->people->first()->image
Because you are getting the image from the first people. But I don't recommend this code because you are getting all people of a post and use just one of them and it's not optimized.
But if you want to show all people use this:
@foreach($employees as $employee)
@foreach($employee->people as $person)
{{ $person->image }}
@endforeach
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.