This should work
$posts = Post::where('user_id', 2)->whereHas('user.country', function ($query) {
$query->where('id', 3);
})->get();
$country = Country::whereHas('users.posts', function ($query) {
$query->where('id', 6);
})->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I would like to understand how should I make an ELEGANT solution for triple table connection relationship with Laravel - Eloquent.
The problem (I stay with the example in the documentation):
1. Country
2. User
3. Post
A 'Country' can own infinity users, and a 'User' can own infinity posts
A 'Post' must belong to a 'User', and a 'User' must belong to a 'Country'.
So as the documentation sais: we can use hasManyThrough connection type.
But i would like something like this (this syntax is only an illustration)
Country::find(3)->users(2)->posts();
I would like to get the Country by id 3, and i need this countries users, and a specific user by id 2 (id or by name or whatever), and the posts of this user, and vica versa:
Post::find(6)->user()->country();
I would like to know the user of the post with id 6, and the country attached to this user.
Is there any simple and elegant way to do this (so achive a simple and clean syntax like this), without custom pivot tables and custom columns?
Please or to participate in this conversation.