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

martinszeltins's avatar

How to get Posts with Comments AND Replies?

So I have 3 tables - Posts, Comments, Replies. I would like to get All Posts with their comments and with the replies of comments. Like this

Posts: [
        id: 1,
        body: 'Post body'
        0 comment: {
             id: 1,
             body: 'Comment body for Post 1'
             0: reply: {
                id: 1,
                body: 'Reply for Comment 1'
             }
        }
]

$posts = Post::with('comment.reply')->get();

How do I need to set up relationships in my Models to make this work? I can't understand...

0 likes
2 replies
Nakov's avatar
Nakov
Best Answer
Level 73

So in your comments table you should have post_id.

Then in your Post model add this:

public function comments()
{
    return $this->hasMany(Comment:class);
}

Same for the replies table it should belong to a Comment

So if you have Reply model add this to the Comment model

public function replies()
{
    return $this->hasMany(Reply::class);
}

Then you can get it like this:

$posts = Post::with('comments.replies')->get();

If your Reply is also a Comment with a parent_id for example, then in your Comment model add this instead:

public function replies()
{
    return $this->hasMany(Comment::class, 'parent_id', 'id');
}

Or just share what is your relationship in your database?

Let me know if this works :)

4 likes
martinszeltins's avatar

Thanks, yes. I needed to add comments() to my Posts model and replies() to my Comments model with a hasMany relationship.

Please or to participate in this conversation.