Home » Php » php – lazy loading vs eager loading for nested comment system

php – lazy loading vs eager loading for nested comment system

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a page that has a question and six comments (parent and children). Under lazy loading Laravel makes exactly 12 mysql queries. I’d like to believe that it’s not the best way to go about it. As the comments grow, this may introduce a problem. Take a look:

enter image description here

6 queries to fetch each user’s info and 6 queries to fetch the comment.

Currently I’m doing this:

 Route::bind('comment', function($comment_id) {
     return Comment::where('id', $comment_id)
         ->whereNull('parent_id')
         ->first() ?? abort(404);
 });

and then I’d lazy load each reply like so: $comment->children recursively.

My question is: should I eager load all this at once, or is it fine? What is the best way to approach a situation like this?

How to&Answers: