I'm using the query builder in my Laravel 8 project to create a monthly sum of all of the deleted users in my application, I'm then outputting two items to use as part of a graph, total and date.
This works well, but, if a month didn't have any data then it would skip straight onto the next month, e.g:
- 2021-01
- 2021-04
- 2021-05
How can I modify the query to add all of the months, from a given start date, up until "now" and effectively add blank values for those months that don't have data?
My current query is:
$data = User::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as date, COUNT(*) as total')
->groupByRaw('DATE_FORMAT(created_at, "%Y-%m")')
->withTrashed()
->whereNotNull('deleted_at')
->get();
And I'm thinking of calculating the start by doing something like this:
$user = User::orderBy('created_at', 'asc')->first();
$start = $user->created_at;
$data = User::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as date, COUNT(*) as total')
->groupByRaw('DATE_FORMAT(created_at, "%Y-%m")')
->withTrashed()
->whereNotNull('deleted_at')
->get();
$end = Carbon::now()->endOfMonth();
Not sure how to get it into the query though