PHP
Efficiently Count Related Models with Eloquent `withCount`
Learn how to retrieve parent models along with the count of their related records using Eloquent's `withCount` method, optimizing database queries.
use App\Models\Post;
// Get all posts and the count of their comments
$postsWithCommentCounts = Post::withCount('comments')->get();
foreach ($postsWithCommentCounts as $post) {
echo "Post: " . $post->title . ", Comments: " . $post->comments_count . "
";
}
// You can also add constraints to the count
$postsWithApprovedCommentCounts = Post::withCount(['comments' => function ($query) {
$query->where('approved', true);
}])->get();
foreach ($postsWithApprovedCommentCounts as $post) {
echo "Post: " . $post->title . ", Approved Comments: " . $post->comments_count . "
";
}
How it works: The `withCount` method adds a `[relationship_name]_count` attribute to the resulting models, indicating the number of related models. This is far more efficient than loading the full relationship and then counting them, as it performs a single subquery for the count rather than loading all related records. It can also be constrained to count specific subsets of related models.