Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract count of each status by month

I have the following database:

Reservations
| id | status    | created_at          |
|  1 | Canceled  | 2019-12-16 11:46:11 |
|  2 | Fulfilled | 2019-11-15 23:03:24 |
|  3 | Accepted  | 2019-12-13 12:04:13 |

So I want to extract a collection by months in which there's the count of each status. I.e.:

['Month', 'Accepted', 'Fulfilled', 'Canceled'],
['Jul 2019', 4, 5, 9],
['Aug 2019', 5, 6, 7]

I have several ways of approaching that but all require additional work outside eloquent and don't look very elegant.

like image 788
OurBG Avatar asked Nov 18 '25 13:11

OurBG


1 Answers

Try using the Collection::countBy() method. (https://laravel.com/docs/master/collections#method-countBy)

Reservation::countBy('status');

You can always constrain your query before calling the countBy() function

like image 131
Spholt Avatar answered Nov 20 '25 19:11

Spholt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!