Laravel 10 Has Many Through Relationship

In Laravel, the "Has Many Through" relationship allows you to define a relationship that traverses through another related model to access a third model. This is useful when you have a relationship between three tables, and you want to access the data of the third table through the intermediate table. The "Has Many Through" relationship simplifies the process of querying and retrieving related records.

Step 1 :Install Laravel App:

composer create-project laravel/laravel example-HashManyThroughRelationship

Step 2: Database Configuration

.env 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name
DB_USERNAME=database username
DB_PASSWORD=database password

Step 3 : Model Setup:

// Country.php model
    class Country extends Model
    {
        public function posts()
        {
            return $this->hasManyThrough(Post::class, User::class);
        }
    }
    
    // User.php model
    class User extends Model
    {
        public function country()
        {
            return $this->belongsTo(Country::class);
        }
    
        public function posts()
        {
            return $this->hasMany(Post::class);
        }
    }
    
    // Post.php model
    class Post extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }

Step 4 : Accessing the Relationship

Once the relationship is defined, you can access it from the Country model. For example, you can retrieve all the posts associated with a country: 

$country = Country::find(1);
$posts = $country->posts; // Access the posts through the country

Additional Operations:

With the defined "Has Many Through" relationship, you can perform various operations such as eager loading, filtering related records, and accessing additional methods or attributes of the intermediate models.

$country = Country::with('posts')->find(1);
    $posts = $country->posts;
    
    foreach ($posts as $post) {
        // Access additional attributes/methods of the post or intermediate models
        $user = $post->user;
        $country = $user->country;
    }

You can also define inverse relationships and perform operations from the other side of the relationship, such as accessing the country from a post.

$post = Post::find(1);
$country = $post->user->country;