Home > Software engineering >  Laravel - How do I get the total number of comments?
Laravel - How do I get the total number of comments?

Time:12-29

I would like to get the total number of comments on a post.

Two models. Post and Comments. Comments has a polymorphic relationship to Post. Comments can have other comments on themselves. They are comments on comments / Replies to a comment. This relationship is represented by the column comment_parent in the comment database table.

Here are my models:

Post

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable')->whereNull('comment_parent');
}

Comments

public function commentable()
{
    return $this->morphTo();
}

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

Blade

In my blade, Count only shows the number of first level comments. All replies to comments do not. How and where can I determine the number of all comments with replies count?

post.blade.php

<h3>Comments ( {{ $post->comments->count() }} )</h3>

@foreach($comments as $comment)
    <div>{{ $comment->content }}</div>

    <!-- show replies -->
    <div>
        @foreach($comment->replies as $reply)
            <div >
        <div>{{ $reply->content }}</div>
            </div>
        @endforeach
    </div>
@endforeach

PostController

public function show(Post $post) {
    $post->load(['comments' => function ($query) {
        $query->where('comment_approved', true)->orderBy('id','desc');
    }]);        
        
    return view('page.post', ['post' => $post]);
}

CodePudding user response:

use a new relation without the condition ->whereNull('comment_parent') and count() on it.

public function allComments()
{
    return $this->morphMany(Comment::class, 'commentable');
}
<h3>Comments ( {{ $post->allComments()->count() }} )</h3>

if you want to do it in the controller

public function show(Post $post) {
    $post->load(['comments' => function ($query) {
        $query->where('comment_approved', true)->orderBy('id','desc');
    }])->loadCount('allComments');        
        
    return view('page.post', ['post' => $post]);
}

then use it in the blade as

<h3>Comments ( {{ $post->all_comments_count }} )</h3>
  • Related