How to get distinict vendors and thier count in laravel?

Viewed 102

I am using Laravel 8 and i want to fetch data of vendor also their count. Means if vendor is Broadway and it appear in invoices 7 time and vendor is ABC and it appear 6 time then i want array as:

Broadway => 7
ABC => 6

I have write this code to fetch monthly invoices,

public function fetchCurrentMonthInvoices()
{
    return Auth::user()->invoices()
        ->whereMonth("invoice_date", Carbon::now()->month)
        ->whereYear("invoice_date", Carbon::now()->year)
        ->get();
}

and i call this function in other function

public function fetchDonutChartData($invoice)
{
   $data = $this->fetchCurrentMonthInvoices();
   $provider = $data->map(function ($invoice){
      return collect($invoice)->only('provider')->all();
   });
   dd($provider);
}

and get result repeated vendors enter image description here How can i get the result.

database structure is enter image description here

1 Answers

I suppose this would work:

$invoices = DB::table('invoices')
             ->select('vendor', DB::raw('count(*) as total'))
             ->groupBy('vendor')
             ->get();
Related