How to optimize my code using sql queries
$collection->filter(function ($item) use ($i) {
return $item->created_at->month == $i->month;
})->count();
I want instead of filter function on a collection to filter in sql so it can be quicker
here is the function :
$data = [];
switch ($range) {
//monthly
case self::$timeRanges[0]:
for ($i = Carbon::now()->copy()->subYear()->endOfMonth(); $i <= Carbon::now()->subMonth()->endOfMonth(); $i->addMonths(1)) {
$data[$i->month] = $collection->filter(function ($item) use ($i) {
return $item->created_at->month == $i->month;
})->count();
}
break;
//weekly
case self::$timeRanges[1]:
$collection = $collection->where('created_at', '>=', Carbon::now()->subWeek()->endOfWeek()->subWeeks(5))->where('created_at', '<=', Carbon::now()->subWeek()->endOfWeek());
for ($i = Carbon::now()->copy()->subWeek()->endOfWeek()->subWeeks(5); $i <= Carbon::now()->copy()->subWeek()->endOfWeek(); $i->addWeeks(1)) {
$data[$i->weekOfMonth] = $collection->filter(function ($item) use ($i) {
return $item->created_at->weekOfYear == $i->weekOfYear;
})->count();
}
break;
}
return ($data);
thanks for helping, and have a nice day!