Laravel - Relationships - Counting Related Models
Sometimes you may want to count the number of related models for a given relationship without actually loading the models. To accomplish this, you may use the withCount
method. The withCount
method will place a {relation}_count
attribute on the resulting models:
use App\Models\Post;
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
By passing an array to the withCount
method, you may add the "counts" for multiple relations as well as add additional constraints to the queries:
use Illuminate\Database\Eloquent\Builder;
$posts = Post::withCount(['votes', 'comments' => function (Builder $query) {
$query->where('content', 'like', 'code%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
You may also alias the relationship count result, allowing multiple counts on the same relationship:
use Illuminate\Database\Eloquent\Builder;
$posts = Post::withCount([
'comments',
'comments as pending_comments_count' => function (Builder $query) {
$query->where('approved', false);
},
])->get();
echo $posts[0]->comments_count;
echo $posts[0]->pending_comments_count;