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.orderBy method do in Laravel's Eloquent?orderByorderBy method is used to sort query results by a column in ascending or descending order.created_at date descending in Laravel?orderBy with column and direction as parameters to sort results.orderBy is correct, desc is lowercase string, and get() fetches results. Other options use invalid methods.$results = DB::table('orders')
->select('status', DB::raw('count(*) as total'))
->groupBy('status')
->orderBy('total', 'desc')
->get();$results contain?status and counts how many orders each status has, naming count as total.total descending, so statuses with more orders appear first.$users = User::groupBy('role')->orderBy('name')->get();having('total', '>', 5) to filter categories with more than 5 sales. where cannot filter aggregated results.orderBy('total', 'desc') after grouping and filtering.Pass the test and this pattern moves unknown