<?php ... $users = DB::table('users') ->selectRaw(" count(id) as total, date_format(created_at, '%b %Y') as period ") ->whereYear('created_at', '>=', 2020) ->groupBy('period') ->get() ->keyBy('period'); $periods = collect([]); foreach (CarbonPeriod::create('2020-01-01', '1 month', now()->subMonth()) as $period) { $periods->push($period->format('M Y')); } $totals = $periods->map(function ($period) use ($users) { return $users->get($period)->total ?? 0; }); return [ 'totals' => $totals->toArray(), 'periods' => $periods->toArray() ];