0

Please I want to count the number of Items in each grouped collection. assuming the collection returns three group Items, I want to count the collection in each group

I did this but it isn't working out for me

$collection = Vendor::all();
$grouped = $collection->groupBy('vendor_discount');
$counted = $grouped->countBy();
return $counted->all();

this is the error am getting back

array_key_exists(): The first argument should be either a string or an integer

by doing this

$user_info = DB::table('vendors')
                 ->select('vendor_discount', DB::raw('count(*) as total'))
                 ->groupBy('vendor_discount')
                 ->get();

this is the results

0: {vendor_discount: null, total: 1}
total: 1
vendor_discount: null
1: {vendor_discount: "10%", total: 2}
total: 2
vendor_discount: "10%"
2: {vendor_discount: "20%", total: 2}
total: 2
vendor_discount: "20%"

how do I correctly display in a view template?

Prince Asamoah
  • 135
  • 3
  • 11

1 Answers1

0

Your Query

$user_info = DB::table('vendors')
                 ->select('vendor_discount', DB::raw('count(*) as total'))
                 ->groupBy('vendor_discount')
                 ->get()->toArray();

return $user_info;

then in the view file

//Loop through the values
foreach($user_info as $user){
    echo $user->vendor_discount." - ".$user->total;
}
Vivek Choudhary
  • 634
  • 8
  • 14