Use withCount() in Laravel to Get Related Data Counts Easily
Imagine you have users and posts. You want to show a list of users along with how many posts each has. The beginner way is to loop and count — but that’s slow and inefficient.
Laravel’s withCount() makes it simple and efficient.
The Inefficient Way
$users = User::all();
foreach ($users as $user) {
echo $user->posts()->count(); // runs a query for each user
}
The Laravel Way – Using withCount()
$users = User::withCount('posts')->get();
foreach ($users as $user) {
echo $user->name . ' has ' . $user->posts_count . ' posts';
}
- Only one query runs.
- Laravel automatically adds a
posts_countattribute to each user. - Clean and efficient!
Real-World Example
You can even count with conditions:
$users = User::withCount([
'posts as published_posts_count' => fn($q) => $q->where('status', 'published')
])->get();
Now each user has a published_posts_count field ready to use.
Final Thought
The withCount() method is a must-know for anyone working with relationships in Laravel. It saves you from the N+1 query problem and makes your code cleaner. Whenever you need counts of related data, think withCount() instead of looping.