0
0
Laravelframework~5 mins

Has-many-through in Laravel

Choose your learning style9 modes available
Introduction

Has-many-through helps you get related data through another model easily. It saves time by linking models indirectly.

You want to get all posts written by authors of a specific country.
You need to list all comments on posts that belong to a certain user.
You want to find all orders placed by customers of a particular company.
You want to access all products sold by suppliers in a specific region.
Syntax
Laravel
public function relatedModels() {
    return $this->hasManyThrough(FinalModel::class, IntermediateModel::class);
}

The first argument is the final model you want to access.

The second argument is the intermediate model that connects the two.

Examples
This gets all posts written by users from a country.
Laravel
class Country extends Model {
    public function posts() {
        return $this->hasManyThrough(Post::class, User::class);
    }
}
This gets all comments on posts written by a user.
Laravel
class User extends Model {
    public function comments() {
        return $this->hasManyThrough(Comment::class, Post::class);
    }
}
Sample Program

This example shows how to get all posts for a country through its users. It prints each post title.

Laravel
<?php

use Illuminate\Database\Eloquent\Model;

class Country extends Model {
    public function posts() {
        return $this->hasManyThrough(Post::class, User::class);
    }
}

class User extends Model {
    // User belongs to Country
}

class Post extends Model {
    // Post belongs to User
}

// Usage example:
$country = Country::find(1);
$posts = $country->posts;
foreach ($posts as $post) {
    echo $post->title . "\n";
}
OutputSuccess
Important Notes

Make sure foreign keys follow Laravel conventions or specify them explicitly.

Has-many-through works only with two levels of relationships.

Summary

Has-many-through links models through an intermediate model.

It helps fetch related data easily without manual joins.

Use it when you want to access data two steps away.