Laravel 9 Group By Query Example

Websolutionstuff | Mar-29-2022 | Categories : Laravel PHP MySQL

In this article, we will see laravel 9 group by query example. how to use group by in laravel 9. As you might expect, the groupBy and having methods may be used to group the query results. learn how to create a collection of data using Laravel groupBy method. It can allow us to group the data by types, id, date etc.

Also, I will give yoy example of laravel 9 group by with where clause and query of group by in mysql. The GROUP BY statement is often used with aggregate functions COUNT()MAX()MIN()SUM()AVG() to group the result-set by one or more columns.

So, let's see  how to use group by in laravel 9, laravel 9 group by multiple, laravel 9 group by with where clause, group by in MySQL,  laravel 9 group by date, group by in laravel 9,

SQL Query :

MySQL Group By Syntax with where condition :

SELECT column_names
FROM table_name
WHERE condition
GROUP BY column_names
ORDER BY column_names;

Example :

SELECT COUNT(user_id), country
FROM users
GROUP BY country;

 

 

Laravel 9 Query :

The “Group By” function belongs to the collection, not eloquent category.

use App\User;
use DB;

public function index()
{
    $users = User::select("*", DB::raw("count(*) as user_id"))
                    ->groupBy('country')
                    ->get();
}

 

Laravel 9 groupBy() with having() query example :

The having method's signature is similar to that of the where method.

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

 

 

Laravel 9 groupBy() with Date

Now, I will give you example of group by date or group by year.

DB::table('users')
      ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
      ->groupBy('date')
      ->get();

 

$users = User::select("*", DB::raw("count(*) as user_count"))
                        ->groupBy(DB::raw("year(created_at)"))
                        ->get();

 


You might also like :

Recommended Post
Featured Post
Laravel 8 One To One Relationship Example
Laravel 8 One To One Relations...

In this example we will see laravel 8 one to one relationship example also you can use one to one relationship in l...

Read More

Nov-01-2021

Multi Step Form Wizard jQuery Validation
Multi Step Form Wizard jQuery...

In this article, we will see multi step form wizard jquery validation. Here, we will learn jquery validation for mu...

Read More

Jan-30-2023

Laravel 9 MongoDB CRUD Operation Tutorial
Laravel 9 MongoDB CRUD Operati...

In this article, we will see the laravel 9 MongoDB crud operation tutorial. In laravel, we will have many crud operation...

Read More

Dec-06-2022

How To Install Vue JS 3 In Laravel 9
How To Install Vue JS 3 In Lar...

In this article, we will see how to install Vue JS 3 in laravel 9. Laravel is a web application framework with...

Read More

Oct-07-2022