-1

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)

enter image description here

Fatih Can
  • 321
  • 4
  • 12

4 Answers4

5

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

e.g.

@foreach($employees as $employee)
   @foreach($employee->people as $person)
      {{ $person->image }}
   @endforeach
@endforeach
Lukas Grofcik
  • 457
  • 1
  • 3
  • 15
2

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
Nikola Vi
  • 114
  • 1
  • 8
0

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

Ketan Vekariya
  • 334
  • 1
  • 11
0

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
baleghsefat
  • 192
  • 3
  • 9