Home / Snippets / Laravel groupBy Full Code Example
Laravel groupBy Full Code Example cover

Laravel groupBy Full Code Example


2 years ago


The "groupBy()" method is available to the "DB" facade and you can use it as follows. Do note that in order to "group by" similar or related records you need to have something for it to count to. In the code example below it's the "user_count".

$users = DB::table('users')
             ->select(DB::raw('count(*) as user_count, status'))
             ->where('status', '<>', 1)
In addition to that, you can also mix "groupBy" with "having" and it's like below. This is very useful when you are grouping a related column but ensure that the condition for that query is met hence it's using the "having" function.

$users = DB::table('users')
                ->having('account_id', '>', 100)
The method signature is the same as the regular "where()" method.

$users = DB::table('users')
                ->groupBy('first_name', 'status')
                ->having('account_id', '>', 100)
Grouping by record with "havingRaw()" method.

$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->havingRaw('SUM(price) > ?', [2500])
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this