BrainyT's avatar

Group data by Month

I have a sales data on a table I want to present in chart like this { "jan": 34, "feb": 30, "mar": 41, "apr": 18, "may": 26, "jun": 21 } How do I query this data with eloquent using created_at to count and group them based on month?

0 likes
5 replies
tykus's avatar

What a fucking vague problem statement... no table name, no context about the aggregation you need, no effort...

\DB::table('table_name')
    ->selectRaw('MONTH('created_at') as month, COUNT(*) as count))
    ->groupByRaw('MONTH('created_at'))
    ->whereYear('created_at', date('Y'))
    ->get();
BrainyT's avatar

@tykus I have a purchases table and what I want to achieve is to show every seller the sales count of months from Jan-Dec using the created_at(Which is the time the product was sold and saved on the table).

juliofagundes's avatar
Model::query()
	->select(\DB::raw('count(*) as total, MONTHNAME(created_at) as month'))
	->groupByRaw('MONTHNAME(created_at)')
	->get()

And then with collection result, you can use keyBy() and other helpers methods to help you organize it

BrainyT's avatar

@juliofagundes Thanks but this is only giving me the count for current month, I want to get counts for Jan, feb to Dec as a key and value e.g. [{ month: "jan", total: 20}, {month: "feb", total: 15}]

Please or to participate in this conversation.