Formatink
5 years ago

Nested comments with eager loading

Posted 5 years ago by Formatink

Hello,

I am currently doing a nested comments system.
In my model, I use this method to retrieve children of the comment

public function children()
{
     return $this->hasMany('App\Models\NewsComment', 'parent_id', 'id');
}

I get my comments like this :

$comments = NewsComment::with('children')
    ->where('parent_id', 0)
    ->where('news_id', $newsId)
    ->get();

and I display my comments like this :

@foreach($comments as $comment)
    @include('pages.news_comment', ['comment' => $comment])
@endforeach

Here is my pages.news_comment.blade.php file

{{ $comment->content }} <br/>

@if ($comment->children->count() > 0)
    @foreach ($comment->children as $comment)
        <div style="margin-left: 30px">
            @include('pages.news_comment', ['comment' => $comment])
        </div>
    @endforeach
@endif

The problem is that it makes a query to get children of each child.
The eager loading works only for the first children.

How could I get all children in advance and avoid this problem ?
Thank you in advance.

Regards,
Formatink

Please sign in or create an account to participate in this conversation.