Laravel 8 Group By Query Example

Websolutionstuff | Nov-29-2021 | Categories : Laravel PHP MySQL

In this example we will see laravel 8 group by query example. how to use group by in laravel 8. 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 8 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 start how to use group by in laravel 6, laravel 7 and laravel 8.

SQL Query :

Group By Syntax :

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

 

 

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

 

Laravel 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 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 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
How To Create Pie Chart In Laravel 9 Using Highcharts
How To Create Pie Chart In Lar...

In this article, we will see how to create a pie chart in laravel 9 using highcharts. A pie chart is a circular statisti...

Read More

Oct-05-2022

How to install GCC on Ubuntu 22.04
How to install GCC on Ubuntu 2...

Hello there! If you're diving into the world of programming on Ubuntu 22.04 and want to get your hands dirty with so...

Read More

Jan-15-2024

Laravel 9 Order By Query Example
Laravel 9 Order By Query Examp...

In this article, we will see laravel 9 order by query example. how to use order by in laravel 9.The orderBy me...

Read More

Mar-28-2022

How To Get Element By Data Attribute In jQuery
How To Get Element By Data Att...

In this article, we'll learn how to locate elements using data-attribute values. We can do this using jQuery and CSS...

Read More

Jul-11-2022