Kareem Nour Emam
Kareem Nour Emam

Reputation: 1054

laravel Eloquent: Relationships get third part relation

iam working in journal project and i have 3 main table related Volumes->issues->articles

volume has many issue but issue has one volume
issues has many articles but article has one issue

all working fine but i have 1 tricky step

i want to get volume name when view all articles. i want view the following when retrieving articles

article name | vol name/issue name

i success to get issue name as i have relation between article module and issue module but i dont know how to get volume name inside for-each articles

<tr>
     <th>Title</th>
     <th>Vol/Issue</th>
</tr>
@foreach($articles as $article)
  <td>{{ $article->title }}
  <td>{{ ??? }} / {{$article->issue->name}}</td>
@endforeach

Upvotes: 0

Views: 519

Answers (1)

Jonathon
Jonathon

Reputation: 16283

Assuming you have the belongs to relations set up in each model to act as the reverse of your has many relations:

class Article extends Model
{
    public function issue()
    {
        return $this->belongsTo(Issue::class);
    }
}

class Issue extends Model
{
    public function volume()
    {
        return $this->belongsTo(Volume::class);
    }
}

You should be able to eager load the issue relation and the issue's volume relation when retrieving your articles, like this:

$articles = Article::with(['issue', 'issue.volume'])->get();

and in your view (Assuming you use the name attribute):

{{ $article->issue->volume->name }}

For more information regarding this, look up "Nested Eager Loading" in the documentation

Upvotes: 1

Related Questions