skip to Main Content

I’m working on a Laravel project and I have two models: "Post" and "Comment". Each post can have multiple comments. I’m trying to use the "withCount" method in Laravel to get the number of comments for each post.

Here’s what my code looks like so far:

$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->title . ' has ' . $post->comments_count . ' comments.';
}

However, when I run this code, the "comments_count" property is always 0, even though I know that some posts have comments.

I’m not sure what I’m doing wrong here. Can someone please help me understand how to properly use the "withCount" method in Laravel to count related models?

Thanks in advance for your help!

2

Answers


  1. Have you defined the One To Many relationship correctly?

    class Post extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function comments(): HasMany
        {
            return $this->hasMany(Comment::class);
        }
    }
    
    Login or Signup to reply.
  2. Define the relationship

    class Post extends Model
    {
        public function comments()
        {
            return $this->hasMany(Comment::class);
        }
    }
    
    class Comment extends Model
    {
        public function post()
        {
            return $this->belongsTo(Post::class);
        }
    }
    

    And in code, access it with comments_count

    $posts = Post::withCount('comments')->get();
    
    foreach ($posts as $post) {
        echo $post->title . ' has ' . $post->comments_count . ' comments.';
    }
    

    Check this Article example – Eloquent withCount(): Get Related Records Amount

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search