Home > Mobile >  Property [image] does not exist on this collection instance. / Laravel - with() Method
Property [image] does not exist on this collection instance. / Laravel - with() Method

Time:12-16

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related