PHP

Complex Relationship with Eloquent `hasManyThrough`

Master the `hasManyThrough` relationship in Laravel Eloquent to access "grandchild" models through an intermediate model, simplifying complex data retrieval.

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

use Illuminate\Database\Eloquent\Model;

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

// In 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);
    }
}

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

use Illuminate\Database\Eloquent\Model;

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

// Example Usage:
$country = Country::find(1);
// Get all posts written by users from this country
$postsFromCountry = $country->posts;

foreach ($postsFromCountry as $post) {
    echo "Post Title: " . $post->title . "
";
}
How it works: The `hasManyThrough` relationship allows you to access a "grandchild" model through an intermediate model. In this example, a `Country` model can directly access all `Post` models associated with `User` models that belong to that country. This simplifies querying data across multiple relationships without manual joins or nested loops.

Need help integrating this into your project?

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

Hire DigitalCodeLabs