Is there a way to skip a certain month? I just need to show January, February, September, October, November and December.
This is my code:
$emptyMonth = ['count' => 0, 'month' => 0];
for ($i = 1; $i <= 12; $i++) {
$emptyMonth['month'] = $i;
$monthlyArray[$i - 1] = $emptyMonth;
}
$data = DB::table('doc')
->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
->where('status', 'done')
->where('created_at', '>=', Carbon::parse('first day of january'))
->where('created_at', '<=', Carbon::parse('last day of december'))
->whereyear('created_at', Carbon::now())
->groupBy('month')
->orderBy('month')
->get()
->toarray();
foreach ($data as $key => $array) {
$monthlyArray[$array->month - 1] = $array;
}
$result = collect($monthlyArray)->pluck('count');
Is there a way to skip or not show some of specific of the month?
you can use whereMonth:
$data = DB::table('doc')
->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
->where('status', 'done')
->where('created_at', '>=', Carbon::parse('first day of january'))
->where('created_at', '<=', Carbon::parse('last day of december'))
->whereyear('created_at', Carbon::now())
->where(function($query){
$query->whereMonth('created_at',1)
->orWhereMonth('created_at',2)
->orWhereMonth('created_at',9); // extra
})
->groupBy('month')
->orderBy('month')
->get()
->toarray();
or simply do it using raw and Month mysql function:
$query->whereIn(DB::raw('MONTH(created_at)'),[1,2,3,9]);