ItSolutionStuff.com

Laravel Group By with Month and Year Example

By Hardik Savani • November 5, 2023
Laravel

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...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Get Array of Ids from Eloquent Models in Laravel

Read Now →

Laravel Eloquent Find by Column Name Example

Read Now →

How to Find Multiple Ids using Laravel Eloquent?

Read Now →

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

Laravel Eloquent doesntHave() Condition Example

Read Now →

Laravel Eloquent Group By Year with Sum Example

Read Now →

Laravel Eloquent Sum Multiple Columns Example

Read Now →

Laravel Eloquent Group By Example

Read Now →

Laravel Eloquent take() and skip() Query Example

Read Now →

Laravel Eloquent whereNotNull() Query Example

Read Now →

Laravel Eloquent exists() and doesntExist() Example

Read Now →

Laravel Eloquent Group By with Multiple Columns Example

Read Now →

Laravel Eloquent Inner Join with Multiple Conditions Example

Read Now →

Laravel Join with Subquery in Query Builder Example

Read Now →