Hello, if you have solved this problem. Please give me the solution with the loop in view.
Aug 8, 2022
3
Level 1
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;
Please or to participate in this conversation.