PHP
Counting Related Models Efficiently with `withCount`
Learn to use Laravel Eloquent's `withCount` method to efficiently retrieve the count of related models without loading all relationships, optimizing performance.
// Get all posts along with the count of their comments
$posts = App\Models\Post::withCount('comments')->get();
// Get users and their published post count, only counting posts that are published
$users = App\Models\User::withCount(['posts' => function ($query) {
$query->where('published', true);
}])->get();
echo "Posts with Comment Counts:
";
foreach ($posts as $post) {
echo "- " . $post->title . " (Comments: " . $post->comments_count . ")
";
}
echo "
Users with Published Post Counts:
";
foreach ($users as $user) {
echo "- " . $user->name . " (Published Posts: " . $user->posts_count . ")
";
}
How it works: The `withCount` method is a powerful Eloquent feature that allows you to count the number of related models for each model in your query without fetching all of the related models themselves. This results in a much more efficient query, adding a `[relationship]_count` attribute to each model. You can also apply conditions to the count.