Laravel Group By with Month and Year Example
Hello Artisan,
This article will give you an example of laravel group by year month. This tutorial will give you a simple example of laravel group by month from date field. In this article, we will implement a laravel group by month and sum. you can understand a concept of laravel group by month example.
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() and YEAR() 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:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ClickController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = DB::table("clicks")
->select("id"
,DB::raw("(SUM(*)) as total_clicks")
,DB::raw('YEAR(created_at) year, MONTH(created_at) month'))
->orderBy('created_at')
->groupBy('year','month')
->get();
dd($data);
}
}
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. 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, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Get Array of Ids from Eloquent Models in Laravel
- Laravel Eloquent Find by Column Name Example
- How to Find Multiple Ids using Laravel Eloquent?
- How to Select Specific Columns in Laravel Eloquent Model?
- Laravel Eloquent doesntHave() Condition Example
- Laravel Eloquent Group By Year with Sum Example
- Laravel Eloquent Sum Multiple Columns Example
- Laravel Eloquent Group By Example
- Laravel Eloquent take() and skip() Query Example
- Laravel Eloquent whereNotNull() Query Example
- Laravel Eloquent exists() and doesntExist() Example
- Laravel Eloquent Group By with Multiple Columns Example
- Laravel Eloquent Inner Join with Multiple Conditions Example
- Laravel Join with Subquery in Query Builder Example