Group by year month example in Laravel 5 using Query Builder

By Hardik Savani | June 20, 2016 | | 79986 Viewer | 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();




Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.