Laravel Eloquent Group By Example

By Hardik Savani April 16, 2024 Category : Laravel

In this short tutorial we will cover an laravel eloquent group by example. we will help you to give example of laravel group by example. you will learn laravel group by query builder. you can understand a concept of group by query in laravel eloquent.

Here, simple example of group by in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.

In this example i will give you very simple example of how to use groupBy() in laravel application. you can easily use it with laravel 6 and laravel 7 application.

groupBy() will help you to getting data with group and you can count number records on that group.

So, let's see bellow examples that will help you how to use groupBy() and groupBy() eloquent query in laravel.

Example 1:

SQL Query:

select *, count(*) as user_count

from `users` group by `status`

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use DB;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*", DB::raw("count(*) as user_count"))

->groupBy('status')

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 7

[name] => Prof. Kelly Kilback

[email] => nader.autumn@example.org

[country_id] =>

[email_verified_at] => 2020-07-01T09:34:13.000000Z

[created_at] => 2020-07-01T09:34:13.000000Z

[updated_at] => 2020-07-01T09:34:13.000000Z

[status] => 0

[first_name] =>

[last_name] =>

[point] =>

[points] => 45

[amount] => 45

[user_count] => 197

)

[1] => Array

(

[id] => 1

[name] => Prof. Josiane Jast MD

[email] => savanihd@gmail.com

[country_id] => 1

[email_verified_at] => 2020-07-01T09:34:13.000000Z

[created_at] => 2020-07-03T09:34:13.000000Z

[updated_at] => 2020-07-01T09:34:13.000000Z

[status] => 1

[first_name] =>

[last_name] =>

[point] =>

[points] => 0

[amount] => 1000

[user_count] => 6

)

)

Example 2: Get Group By with Year

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use DB;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*", DB::raw("count(*) as user_count"))

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

->get();

dd($users);

}

}

I hope it can help you...

Shares