Ricki Moore
Ricki Moore

Reputation: 1223

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

Upvotes: 4

Views: 17783

Answers (2)

Elie Fa&#235;s
Elie Fa&#235;s

Reputation: 3315

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

Upvotes: 7

Santiago Mendoza Ramirez
Santiago Mendoza Ramirez

Reputation: 1657

I think your problem is because not following laravel "assumes". In documentation:

Additionally, Eloquent assumes that the foreign key should have a value matching the id column of the parent. In other words, Eloquent will look for the value of the user's id column in the user_id column of the Phone record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

What is the id of Hero? If it's different than id, then you have to add the local_key name.

Upvotes: 1

Related Questions