PHP

Defining a Has Many Through Eloquent Relationship

Understand how to define and query a 'has many through' relationship in Laravel Eloquent to access distant relations via an intermediate table, simplifying data access.

// app/Models/Country.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

class Country extends Model
{
    // A Country has many Posts through its Users
    public function posts(): HasManyThrough
    {
        return $this->hasManyThrough(Post::class, User::class);
    }

    // A Country has many Users directly (for context)
    public function users()
    {
        return $this->hasMany(User::class);
    }
}

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function country()
    {
        return $this->belongsTo(Country::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

// app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// Database structure (simplified):
// countries: id, name
// users: id, country_id, name
// posts: id, user_id, title

// Usage Example
$country = Country::find(1);

// Get all posts for this country via its users
$posts = $country->posts;

foreach ($posts as $post) {
    echo "Post Title: " . $post->title . "
";
}

// You can also add constraints
$activePosts = $country->posts()->where('posts.active', true)->get();
How it works: The `hasManyThrough` relationship provides a convenient shortcut for accessing distant relations via an intermediate relationship. In this example, a `Country` model can access `Post` models "through" the `User` model, without explicitly querying `User` first. Laravel automatically handles the necessary joins, making it easy to retrieve deeply nested related data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs