Group by year month example in Laravel using Query Builder

By Hardik Savani September 5, 2020 Category : Laravel

Sometimes, we have created_at column with timestamp and we wanted to get with group by with month, that way we can use for chart. However, you can do it using mysql MONTH() function. we can use DB raw with mysql function and get group by monthly records.

So, you can see bellow query and use it.

Example:

DB::table("clicks")

->select("id" ,DB::raw("(COUNT(*)) as total_click"))

->orderBy('created_at')

->groupBy(DB::raw("MONTH(created_at)"))

->get();

We are Recommending you