ItSolutionStuff.com

Laravel Group By Date and Sum Example

By Hardik Savani β€’ April 16, 2024
Laravel

Hi Dev,

This post will give you example of laravel group by date and sum example. I’m going to show you about laravel group by date d-m-y format. This article will give you simple example of laravel group by date format example. let’s discuss about group by date in laravel eloquent example.

Sometimes, we have created_at column with timestamp and we wanted to get with group by with date, that way we can use for chart. However, you can do it using mysql DATE_FORMAT() function. we can use DB raw with mysql function and get group by date records. you can easily use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

Let's see bellow example:

Table:

Laravel Eloquent Query:

<?php

namespace App\Http\Controllers;

use App\Models\Visitor;

use DB;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$visitors = Visitor::select(

"id" ,

DB::raw("(sum(click)) as total_click"),

DB::raw("(DATE_FORMAT(created_at, '%d-%m-%Y')) as my_date")

)

->orderBy('created_at')

->groupBy(DB::raw("DATE_FORMAT(created_at, '%d-%m-%Y')"))

->get();

dd($visitors);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[total_click] => 4

[my_date] => 26-10-2020

)

[1] => Array

(

[id] => 2

[total_click] => 59

[my_date] => 23-09-2021

)

[2] => Array

(

[id] => 6

[total_click] => 12

[my_date] => 04-10-2021

)

[3] => Array

(

[id] => 4

[total_click] => 55

[my_date] => 11-10-2021

)

)

i hope it can help you...

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

β˜…

Laravel Eloquent When Condition Example

Read Now β†’
β˜…

Laravel Eloquent Left Join Where Null Condition Example

Read Now β†’
β˜…

Laravel Eloquent Group By Example

Read Now β†’
β˜…

Laravel Eloquent Order By Query Example

Read Now β†’
β˜…

Multiple orWhere Condition in Laravel Eloquent

Read Now β†’
β˜…

How to Group By with Order By Desc in Laravel?

Read Now β†’
β˜…

Laravel Collection GroupBy with Examples

Read Now β†’
β˜…

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now β†’
β˜…

Laravel Groupby Having with DB::raw() Example

Read Now β†’
β˜…

Laravel Group By with Month and Year Example

Read Now β†’
β˜…

Laravel Eloquent Group By with Multiple Columns Example

Read Now β†’
β˜…

Laravel Select with Count Query with Group By Example

Read Now β†’