Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through relationships Laravel

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
like image 898
Ricki Moore Avatar asked Feb 09 '23 11:02

Ricki Moore


1 Answers

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
like image 96
Elie Faës Avatar answered Feb 11 '23 18:02

Elie Faës