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
Have you defined the One To Many relationship correctly?
Define the relationship
And in code, access it with
comments_count
Check this Article example – Eloquent
withCount()
: Get Related Records Amount