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():

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

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

1@foreach ($users as $user)
2<tr>
3 <td>{{ $user->name }}</td>
4 <td class="text-center">{{ $user->posts_count }}</td>
5 <td class="text-center">{{ $user->comments_count }}</td>
6</tr>
7@endforeach

You may also order by that field:

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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord