Chartjs-How to sum value by month and assign two different variables?

1👍

You could do it all in the query:

$data = Payment::selectSub('MONTH(created_at)', 'month')
    ->selectSub('SUM(payment_amount)', 'total_payments')
    ->groupBy('month')
    ->get();

UPDATE

To separate your controller would look like:

public function index()
{
    $data = Payment::selectSub('MONTH(created_at)', 'month')
        ->selectSub('SUM(payment_amount)', 'total_payments')
        ->groupBy('month')
        ->get();

    return view('admin.dashboard', compact('data'));  
}

Then in our view:

var barChartData = {
    labels: {{ $data->pluck('month') }}, //by month.
    datasets: [{
        label: 'Revenue',
        backgroundColor: "rgba(220,220,220,0.5)",
        data:  {{ $data->pluck('total_payments') }}, //summed up by month
    }]
};

Leave a comment