groupBy() should not be used in withCount() , since withCount() is going to load an account of all elements of the products collection for each Brand , grouped by Brand in the returned collection. This would be equivalent to $brand->products->count() on one Brand .
Between the two examples, groupBy() not required unless you are using this data elsewhere. If so, then it might be better to access your totals in collections as:
//Controller $brands = \App\Models\Brand::with('products')->get(); //View @foreach($brands as $brand) <div>TOTAL PRODUCTS: {{ $brand->products->count() }}</div> @foreach($brand->products->groupBy('extra_attribute') as $attribute => $products) <div>TOTAL {{ $attribute }}: {{ $products->count() }}</div> @endforeach @endforeach
- OR -
You can have the best of both worlds and attach an account and a grouped relationship by simply doing both:
$brands = \App\Models\Brand::withCount('products') ->with(['products' => function ($query) { return $query->groupBy('extra_attribute'); }])->get();
Then you can access the products_count brand and grouped products:
$brands->each(function($brand) { $brand->products_count; $brand->products->each(function($products, $extra_attribute) {
source share