Eloquent has one less-known function called withCount(): it helps to get the amount of related records inside of the main object.
So in this case, we will have $user->posts_count and $user->comments_count variables.
Then, in our Blade file we have this: @foreach ($users as $user) @endforeach
User Posts Comments
{{ $user->name }} {{ $user->posts_count }} {{ $user->comments_count }}
Notice, that withCount() works with both hasMany() relationship, and also 2nd level deep with hasManyThrough().
Another example is that we can even filter the query with withCount() relationship.
More examples of withCount() method – in the official Laravel documentation.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Community Partners