Laravel/PHP Articles

Articles from Laravel/PHP sites on the web

Laravel/PHP Articles
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: User Posts Comments @foreach ($users as $user) {{ $user->name }} {{ $user->posts_count }} {{ $user->comments_count }} @endforeach 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.

Sign Up For Our Newsletter

Each Week, We curate the top Laravel/PHP articles, jobs, events and More!

We'll send you a weekly email with the latest Laravel/PHP articles, jobs and events. Please review our Code of Conduct in the meantime. Talk to you soon!