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

connecteev's avatar

Eloquent Query to get Counts at every level of nesting in a Polymorphic one-to-many relationship

Quick Side Note: I have more than open question I am trying to solve based on this same code. Also see this.

I have the following schema and code in my Laravel application for one-to-many polymorphic relations

  • Users create Posts
  • Post HasMany Comments
  • Post HasMany Reactions

Here,

  • Comment is polymorphic on Post or Comment (commentable_id and commentable_type tell you if the comment is on a Post or a Comment)
  • Reaction is polymorphic on Post or Comment (reactable_id and reactable_type tell you if the reaction ('like') is on a Post or a Comment)

The gist includes:

  1. The models:
  • app/Comment.php . (has a function called nestedComments() that gets comments recursively)
  • app/Post.php
  • app/Reaction.php
  1. Controller (API) code to retrieve nested (recursive) comments on a post, with unlimited levels of nesting.

  2. The SQL schema for posts, comments, reactions tables.

I am trying to solve this:

At each level of nested comments, I need counts of num_likes (number of reactions to the immediate comment) and num_comments (number of immediate sub-children) at each level of nested comments.

So I need an Eloquent Query to get Counts at every level of nesting in a Polymorphic one-to-many relationship.

I already have nested results coming back, but counts don't work (my current implementation of withCount( ) isn't consistent - I dont get counts beyond 2 levels deep....and as you will see in the code I have commented out below, it causes ~10 seconds of slowness...that's not an exaggeration).

See these commented-out blocks of code in

How can you get the counts of num_comments and num_likes efficiently at unlimited levels of nested comments, without retrieving ALL of the comments and likes (reactions), which is what I am currently doing?

0 likes
2 replies
mansoorkhan's avatar

Any luck? Did you find solution to this problem.

I have a similar schema and i need to get the count comments along with nested comments basically count of all comments for a model.

Please or to participate in this conversation.