PHP
Get Count of Related Models Without Loading All
Efficiently retrieve the count of related models for each parent model using Eloquent's `withCount` method in Laravel, preventing N+1 query issues.
use App\Models\User;
use App\Models\Post;
$users = User::withCount('posts')->get();
foreach ($users as $user) {
echo "User {$user->name} has {$user->posts_count} posts.
";
}
// You can specify multiple relationships or alias the count
$categories = Category::withCount(['products', 'products as active_products_count' => function ($query) {
$query->where('is_active', true);
}])->get();
foreach ($categories as $category) {
echo "Category {$category->name} has {$category->products_count} total products and {$category->active_products_count} active products.
";
}
How it works: The `withCount` method efficiently counts the number of related models for each record in the parent query without loading the actual relationship models. This adds a `[relation]_count` attribute (e.g., `posts_count`) to the parent model, making it highly optimized for displaying aggregate counts and avoiding potential N+1 query problems that arise from iterating and counting relationships manually.