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);
withCountmethod is used for counting relationships you haven't retrieved.UserView:findOrFail($userId)->groups()->count();will count the result of your query.