Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

robertmylne's avatar

Eloquent HasManyThrough Nested deeper

I have an eloquent relationship that I am trying to achieve.

So far I have :

Country

Users (country_id)

Posts (user_id)

Comments (post_id)

Now if I want to get all users from a country I do:

    public function users()
    {
        return $this->hasMany('App\Http\Models\User');
    }

If I want to get all posts from a country I do:

    public function posts()
    {
        return $this->hasManyThrough('App\Http\Models\Posts', 'App\Http\Models\User');
    }

How can I go about getting all comments from a country as the link is country->users->posts->comments?

Is there a way to go deeper such as nested hasManyThrough?

0 likes
9 replies
pmall's avatar

No you cant go deeper.

then what you can do depends on what you want to achieve. Arn't nested foreach sufficients ?

robertmylne's avatar

I want to have a page called Australia for example. Then to have it display all comments from Australia.

Country::find(1)->comments;
robertmylne's avatar

@JarekTkaczyk I found that tutorial a bit hard for me as a beginner to understand, it looks interesting and I may give it a go in the future.

@pmall thanks that is what I was trying to achieve. Shame there isn't an Eloquent way to do it.

One last question, I want the country to be dynamically set based on the user visiting. Which I have done. How can I create a global variable that will save this as soon as they hit the site. So I can then for the duration of the visit display relevant information?

$COUNTRY_SET = 7 (Australia); // Global variable accessible through whole site.

$country = Country::find($COUNTRY_SET);
pmall's avatar

How can I create a global variable that will save this as soon as they hit the site. So I can then for the duration of the visit display relevant information?

It is called session data ;)

pmall's avatar

Anyway I think in this case nested foreach are better than a jarektrick. Lets say someone else review your code, he sees nested loops and instantly understand. Jarektricks involve a light wtf moment haha :)

staudenmeir's avatar

I created a HasManyThrough relationship with unlimited levels: Repository on GitHub

After the installation, you can use it like this:

class Country extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function comments() {
        return $this->hasManyDeep(Comment::class, [User::class, Post::class]);
    }
}

Please or to participate in this conversation.