code blocks...
1) 3 backticks on it's own line
2) your code after that
3) a new line with 3 closing backticks.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi guys. How to fetch data from third table connected by eloquent' relationships ? I have eg. 3 tables: Users -> Posts -> Comments
User' model:
``` public function posts() { return $this->hasMany('App\Post'); }
``` Post' model:
``` public function comments() { return $this->hasMany('App\Comment'); }
public function user()
{
return $this->belongsTo('App\User');
}
```
Comment'model:
`` public function post() { return $this->belongsTo('App\Post'); }
So when I want fetch only posts belonging to user I do: foreach($user->posts as $post), but if I want all coments belonging to specific user' post ? I have this:
``` $User->posts->comments
``` it returns:
Property [comments] does not exist on this collection instance.
so I tried: foreach($user->posts as $post) and foreach($post->comments as $comment) but I think that it's bad. Btw what if I want additional fetch data from other table connected with commens ?
the whole code is just an example. Thanks for help!
You have used User->hasMany->post->hasMany->comment so $user->post->comment cannot be accessed.
Users all post and all comment
$user = User::with('posts.comments')->get();
foreach($user->posts as post) {
foreach($post->comments as $comment) {
}
}
User specific post and comments
$user = User::with(['posts' => function($query) { $query->where('post_id', $specific_id)->first }, 'posts.comments'])->get();
foreach($user->posts->comments as $comment) {
// all comments
}
Please or to participate in this conversation.