vendredi 28 décembre 2018

Laravel - return data group by month(and sum) and group by year

I have this function below, which i got to it thanks to the help of everyone in this question:

$records = TabelaAngariacao::select('preco', 'created_at')
            ->where('estado', '=', 'Vendido')
            ->get()
            ->groupBy(function($date) {
                return Carbon::parse($date->created_at)->format('m');
            })->transform(function ($value) { //it can also be map()

                $nStr = $value->map(function ($vl) {
                    return str_replace(".", "", $vl->preco);
                });
                return [
                    'preco_sum' => $nStr->sum()
                ];
            });

...this function is great, i had a problem because i´m saving the preco(prices) has varchar(which is wrong), but by using map i´m able to sum, and everything is working great giving me the result below:

10: {preco_sum: 160000}
11: {preco_sum: 220000}
12: {preco_sum: 1175000}

I have the months and the sum of them...but...then i realize i need to have the same thing but also related to the year, so i tried this:

return Carbon::parse($date->created_at)->format('Y-m');

which leads me to this result:

"2018-10" => array:1 [▶]
"2018-11" => array:1 [▶]
"2018-12" => array:1 [▶]
"2019-01" => array:1 [▶]

but how do i filter this by year on the client side?. I´m using chartjs, so one line should be all the months sumed OF 2018 and the same for 2017 for example.

Thanks for your time, regards



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire