Get count of eager loading relationship in Laravel

This is how I do it

        $user = $this->users->get(auth()->user()->id);
        $user->loadCount('collections');
        $collectionsCount = $user->collections_count;

        $membersCount = 0;
        tap($user->joinedAsManagerCollections()->get(), function ($collections) use (&$membersCount) {
            $collections->each(function ($collection) use (&$membersCount) {
                $collection->loadCount('members');
                $membersCount += $collection->members_count;
            });
        });

Leave a comment