laravel sagmetic
laravel sagmetic

Reputation: 242

How to use the "withCount" method in Laravel to count related models?

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!

Upvotes: 1

Views: 3038

Answers (2)

Abdulla Nilam
Abdulla Nilam

Reputation: 38672

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

Upvotes: 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);
    }
}

Upvotes: 0

Related Questions