Group By Query in Laravel Eloquent Example

August 5, 2020 | Category : Laravel

This simple article demonstrates of group by query in laravel eloquent. We will use laravel count group by query. if you want to see example of laravel group by raw query then you are a right place. if you have question about laravel group by query then i will give simple example with solution.

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