Reputation: 534
I'am trying to create a morrisJS line chart that shows data per month. So i get the data per month like this:
$intakes = Intakes::whereYear('created_at', '=', 2018)
->orWhere(function ($query) {
$query->whereMonth('created_at', '=', 1)
->whereMonth('created_at', '=', 2)
->whereMonth('created_at', '=', 3)
->whereMonth('created_at', '=', 4)
->whereMonth('created_at', '=', 5)
->whereMonth('created_at', '=', 6)
->whereMonth('created_at', '=', 7)
->whereMonth('created_at', '=', 8)
->whereMonth('created_at', '=', 9)
->whereMonth('created_at', '=', 10)
->whereMonth('created_at', '=', 11)
->whereMonth('created_at', '=', 12);
})
->get();
But that would return all the records, in the range from month 1 to 12. But what i want is the data per month, can this be achieved apart from just creating multiple variables like this ?
$intakesMonth1 = Intakes::whereYear('created_at', '=', 2018)
->whereMonth('created_at', '=', 1)
->get();
$intakesMonth2 = Intakes::whereYear('created_at', '=', 2018)
->whereMonth('created_at', '=', 2)
->get();
I hope that i'm clear enough and someone knows a better solution.
Upvotes: 3
Views: 2026
Reputation: 163798
If you want an Eloquent solution, use whereMonth()
:
for($i = 1; $i < 13; $++) {
$intakes[$i] = Intakes::whereMonth('created_at', $i)->get();
}
You can also, get all intakes for the year and then use where()
Laravel Collections method to get intakes for one month only:
$oneMonthData = $collection->where('created_at', '>', Carbon::parse($someDateString)->startOfMonth())->where('created_at', '<', Carbon::parse($someDateString)->endOfMonth());
Upvotes: 5
Reputation: 578
$intakes = Intakes::whereDate('created_at', '<=', '01-01-2018 00:00:00')->whereDate('created_at', '<=', '01-02-2018 23:59:59')->get();
Upvotes: 0