Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joneyspark's avatar

Laravel group by month with shop sales total

I tried to build a Line chart where I have multiple shops and the monthly sales report will be shown with the shop name. I can achieve the monthly data or yearly data but how do I can get the groupBy Month sales total for each shop group array data as my desired line chart data? I share some of my code and screenshot. Please have a look and if you can help me. Thanks

shops table

enter image description here

sales table

enter image description here

my line chart expected data

enter image description here

I know I have to join sales and shops table and I can able to get the shops group data but how to get the shop group monthly sales total?

$sales = Sale::select(
            DB::raw('year(created_at) as year'),
            DB::raw('month(created_at) as month'),
            DB::raw('sum(total) as total'),
        )
            ->where(DB::raw('date(created_at)'), '>=', Carbon::now()->startOfYear())
            ->orderBy('month')
            ->groupBy('year','month')
            ->get()
            ->groupBy(['year', 'month']);
0 likes
0 replies

Please or to participate in this conversation.