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