Loop through relationships Laravel

Ricki Moore

Stackoverflow,

What I want to accomplish:

I want to Loop through the database to find all the (Heroes) with their related (Interview). I want to also pull each Interview with it's related (Story) and (Image). So far I can dd($heroes) and I can see the array correctly grab each hero with their interview and each interview has it's associated image and story. How do I loop through this correctly?

Error

Invalid argument supplied for foreach() (View: /Users/plastics1509moore/Desktop/elephant_gin/resources/views/administration/index.blade.php)

This is what I have done:

Controller:

$heroes = Hero::with('Interview', 'Interview.stories', 'Interview.images')->orderBy('position', 'asc')->get();

Model Relationships:

Hero:

public function Interview()
{
    return $this->hasOne('App\Interview', 'heroInt_id');
}

Interview:

    public function relationships()
{
    return $this->belongsTo('App\Hero');
}
public function stories()
{
    return $this->hasMany('App\InterviewStory');
}
public function images()
{
    return $this->hasMany('App\InterviewImage');
}

InterviewImage:

 public function relationships()
{
    return $this->belongsTo('App\Interview');
}

InterviewStory

public function relationships()
{
    return $this->belongsTo('App\Interview');
}

Html:

Loop:

    @foreach($heroes as $hero)
       @foreach($hero->Interview as $story)
         <div>{{$story->id}}</div>
        @endforeach    
    @endforeach
PeterPan666

You can't loop on Interview because this a hasOne relationship. What you might want to do is

@foreach($heroes as $hero)
   @foreach($hero->interview->stories as $story)
     <div>{{$story->id}}</div>
    @endforeach    
@endforeach

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related