php - Laravel9: how to group wherebetween query by month and year

I have a query in which I am trying to display on a line chart the total spent between 2 dates. In order to do that I need to fetch the total of each month of the year and also to group it by month of the year.

My current query fetches me the current result but I would need to fetch it with the current year aswell.

The query is:

$thisyearcolete = colete::query()

->whereBetween('created_at',['2022-10-10','2022-11-11'])

->selectRaw('month(created_at) as month')

->selectRaw('SUM(totaleuro) as totaleuro')

->groupBy('month')
->orderBy('month')
->pluck('totaleuro','month')
->toArray();

And it displays the following

^ array:2 [?�?
  9 => "450.00"
  10 => "250.00"
]

But I would want to look something like this.

^ array:2 [?�?
  11-2022=> "450.00"
  10-2022=> "250.00"
]

Answer

Solution:

You can create the query using the grouped criteria.

->selectRaw('MONTH(created_at)+YEAR(created_at) as month_year')
->groupBy(\DB::raw('MONTH(created_at)+YEAR(created_at)')

This is an example use the convert/cast required

Or you can use GroupBy in Laravel Collecion Collection Selecting Year and Month and looping

Source