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,
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;
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();
}
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();
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 :
In this article, we will see laravel 9 cron job task scheduling tutorial, many times we require to run some piece o...
Mar-17-2022
Hello developers! Today, we're diving into the wonderful world of Laravel 10 and Livewire to create a Select2 d...
Feb-16-2024
In this example, we will see how to get the last 7 days record in laravel 8. You can simply get the last 7 days record u...
Jan-31-2022
In this article, we will see how to send mail using gmail in laravel 9. we will learn laravel 9 to send mail u...
Aug-03-2022