Skip to content
Advertisement

Laravel: How to get count of total Comments of total Posts

I have 10000 posts and each post have many comments. I need to calculate all comments count when i take posts.

[
    'post_1' => [
        'comments' => [
            'comment_1' => 'trst comment',
            'comment_2' => 'trst comment',
            'comment_3' => 'trst comment',
        ],
    ],
    'post_2' => [
        'comments' => [
            'comment_1' => 'trst comment',
            'comment_2' => 'trst comment',
            'comment_3' => 'trst comment',
        ],
    ],
    'post_3' => [
        'comments' => [
            'comment_1' => 'trst comment',
            'comment_2' => 'trst comment',
            'comment_3' => 'trst comment',
        ],
    ],
]

there are total 9 comments. i want get this count.

In laravel is possible to get count of hasMany relation of one row

Post::first()->comments()-count()

I need like this:

Post::get()->comments()-count()

i dont want use foreach because my server may get down.

Advertisement

Answer

You could do in at least two ways.

$posts = Post::withCount('comments')->get();
$total = $posts->sum('comments_count');
  • Counting directly from the Comment model (in your case, I’ll go for this approach):
$total = Comment::count();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement