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

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners