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

littlebox's avatar

multiple eloquent relations in view

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!

0 likes
7 replies
Cronix's avatar

code blocks...

1) 3 backticks on it's own line
2) your code after that
3) a new line with 3 closing backticks.
Snapey's avatar

Please go back and study the documentation and the Laravel from scratch series.

There could be multiple issues here.

You need to load the comments. These can be eager loaded like;

$posts = $user->posts()->with('comments')->get();
littlebox's avatar

I wrote only the methods that I needed for an example, why comments can be eager loaded ? It's just multiple relation. Thanks

biishmar's avatar
biishmar
Best Answer
Level 11

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
}

littlebox's avatar

Thank u! I read yesterday documenation and something like this I found but here you explained.

Please or to participate in this conversation.