PHP
Get Related Model Counts Efficiently with Eloquent `withCount`
Learn how to use Laravel Eloquent's `withCount` method to retrieve the number of related models without loading the entire relationship, optimizing database queries and improving performance.
use App\Models\User;
use App\Models\Post;
// In User.php model
// public function posts()
// {
// return $this->hasMany(Post::class);
// }
// Retrieve all users and their post count
$users = User::withCount('posts')->get();
foreach ($users as $user) {
echo "User: {$user->name}, Posts Count: {$user->posts_count}
";
}
// You can also add conditions to the count
$usersWithActivePosts = User::withCount(['posts' => function ($query) {
$query->where('is_published', true);
}])->get();
foreach ($usersWithActivePosts as $user) {
echo "User: {$user->name}, Active Posts Count: {$user->posts_count}
";
}
How it works: The `withCount` method allows you to add a `[relation]_count` attribute to your model without actually loading the entire related collection. This is extremely efficient for displaying counts, such as the number of comments on a post or posts by a user, reducing the amount of data retrieved from the database and avoiding N+1 query problems when only the count is needed. You can also apply constraints to the count using a closure.