Concept Flow - Ordering and grouping
Start Query Builder
Apply GroupBy
Apply OrderBy
Execute Query
Get Results
This flow shows how Laravel's query builder applies grouping first, then ordering, before running the query to get results.
DB::table('users') ->select('role', DB::raw('count(*) as total')) ->groupBy('role') ->orderBy('total', 'desc') ->get();
| Step | Action | Query Part | Effect | Result Preview |
|---|---|---|---|---|
| 1 | Start Query Builder | FROM users | Prepare base table | No data fetched yet |
| 2 | Select columns | SELECT role, count(*) as total | Prepare columns and count | No data fetched yet |
| 3 | Apply groupBy | GROUP BY role | Groups rows by role | Rows grouped by role |
| 4 | Apply orderBy | ORDER BY total DESC | Sort groups by count descending | Groups ordered by total desc |
| 5 | Execute query | Run SQL | Fetch grouped and ordered data | Returns grouped roles with counts sorted |
| 6 | Get results | Collect data | Results ready for use | [{"role": "admin", "total": 5}, {"role": "user", "total": 3}] |
| Variable | Start | After groupBy | After orderBy | Final |
|---|---|---|---|---|
| query | DB::table('users') | Grouped by role | Ordered by total desc | Executed and fetched results |
| results | null | null | null | [{"role": "admin", "total": 5}, {"role": "user", "total": 3}] |
Laravel Ordering and Grouping:
- Use groupBy('column') to group rows.
- Use select with DB::raw('count(*) as alias') for counts.
- Use orderBy('alias', 'desc') to sort grouped results.
- groupBy runs before orderBy.
- Call get() to execute and fetch results.