Laravel Eloquent Lazy Eager Load Count
You can use withCount() like this:
<?php
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
You can even eager load relationships count by default by declaring this in your model:
<?php
// Post model
protected $withCount = ['comments'];
also you can use loadCount(): loadCount()
is available since Laravel 5.8
$post->loadCount('comments');
$post_id = $post->id
$comments_count = $post->comments_count;