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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners