Laravel Eloquent Group By Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

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

Hello Brother, simple lesson of group by in laravel 6, laravel 7 and laravel 8.

In this lesson i will give you very simple lesson 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 lessons that will help you how to use groupBy() and groupBy() eloquent query in laravel.

Lesson 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);

}

}

Result:-

Array

(

[0] => Array

(

[id] => 7

[name] => Prof. Kelly Kilback

[email] => nader.autumn@lesson.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

)

)

Lesson 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);

}

}

thank you very much for following up with me.

Recent Posts

Related Posts