Skip to main content
Quick Tip

Use withCount() to Calculate Child Relationships Records

If you have hasMany() relationship, and you want to calculate “children” entries, don’t write a special query. For example, if you have posts and comments on your User model, write this withCount():

public function index()
{
$users = User::withCount(['posts', 'comments'])->get();
return view('users', compact('users'));
}

And then, in your Blade file, you will access those number with {relationship}_count properties:

@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td class="text-center">{{ $user->posts_count }}</td>
<td class="text-center">{{ $user->comments_count }}</td>
</tr>
@endforeach

You may also order by that field:

User::withCount('comments')->orderBy('comments_count', 'desc')->get();

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

[NEW] Marketing for Developers in 2026

7 lessons
52 min

Practical Laravel Security: Packages, Secrets, Supply-Chain Attacks

7 lessons
43 min read

Queues in Laravel 13

18 lessons
1 h 12 min read