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

unknownUser17's avatar

Laravel: Get monthly sales year by year

I am trying to get month sales including 0 sales, for current year and past 3 years.

I need the output like:

|Sales | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | Total ($) | 
| 2019 | 12  | 0   | 10  | 8   | 8   | 0   | 6   | 2   | 0   | 5   | 11  | 1   | 63        | 
| 2020 | 0   | 0   | 11  | 5   | 6   | 4   | 0   | 2   | 8   | 8   | 20  | 6   | 70        | 
| 2021 | 10  | 5   | 5   | 10  | 0   | 6   | 2   | 0   | 9   | 5   | 8   | 3   | 59        | 
| 2022 | 6   | 0   | 0   | 2   | 6   | 0   | 0   | 10  | 8   | 15  | 7   | 11  | 65        | 

The query I have so far, how to I group the sales by month first, then only group by current year and past 3 year. Also how to I get the total sales for each year?

$sales = Member::select(
            DB::raw('year(created_at) as year'),
            DB::raw('month(created_at) as month'),
            DB::raw('sum(price) as price'),
        )
        ->whereBetween('created_at', [$request->startDate, $request->endDate]) // filter sales by date
        ->where(DB::raw('date(created_at)'), '>=', "2019-01-01")
        ->groupBy('year')
        ->groupBy('month')
        ->get()
        ->toArray();
return $sales;
0 likes
3 replies
malikoo's avatar

Hello, if you have solved this problem. Please give me the solution with the loop in view.

1 like
tisuchi's avatar

@malikoo Why not create a new discussion and share your problem explicitly?

1 like

Please or to participate in this conversation.