Laravel Eloquent Group By Example

By Hardik Savani | August 5, 2020 | 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.

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] => [email protected]

[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] => [email protected]

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




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.

We are Recommending you: