0

I don't know what's the best title for my question, but basically I want to select all the group of a user then count it all.

Currently, I have

 $userGroups = UserView::findOrFail($userId) ->groups() ->get(); 

which gives me groups of the user. I could do a foreach after to count it, but was wondering if there is a direct way. I tried adding withCount() in different ways, but didn't manage to make it work.

I could make it work with something like this, but it also gives the user data which I don't need. I only need the groups of the user. This is the reason why the title of the question is like that.

 $userGroups = UserView::with([ 'groups' ]) ->withCount('groups AS groupCount') ->findOrFail($userId); 
2
  • The count method is what you're looking for, have you tried that? The withCount method is used for counting relationships you haven't retrieved. UserView:findOrFail($userId)->groups()->count(); will count the result of your query. Commented Feb 1, 2018 at 14:26
  • That gives me the number only. I want all the groups, then the count afterwards. Commented Feb 1, 2018 at 14:28

1 Answer 1

2

You can use count on a collection too, just $userGroups->count() after you run your query.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.