userPlus
userPlus

Reputation: 349

How to count relations in laravel

How can I count for example the number of roles for a user?

When I try this:

User::with('roles')->count();

it just counts the number of users.

What I need is to return the number of roles per user. For example:

[
   {
     "id": 2,
     "name": "user",
     "roles": 2 
   },
   {
     "id": 3,
     "name": "user",
     "roles": 1 
   }
]

Upvotes: 0

Views: 103

Answers (2)

Jerodev
Jerodev

Reputation: 33186

If you already have the $user object, you can do the following:

$rolecount = $user->roles()->count();

Or if you are using eager loading you can drop the ( & ) at roles

$rolecount = $user->roles->count();

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219920

Eloquent does not support this out-of-the-box.

You can read this great article on how to achieve this:

How to get hasMany relation count efficiently?

Upvotes: 1

Related Questions