0

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 } ] 

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Great article indeed, this method is what I use every time I come across this
0

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(); 

1 Comment

The OP has a collection of users. Doing this for each user means an extra query for every single user. That's terribly inefficient.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.