Ordering and grouping help organize data so it is easier to understand and use. Ordering sorts data by a rule, and grouping collects similar items together.
Ordering and grouping in Laravel
Model::orderBy('column', 'direction')->get(); Model::groupBy('column')->select('column', DB::raw('count(*) as total'))->get();
orderBy sorts the results by a column in ascending ('asc') or descending ('desc') order.
groupBy groups rows that have the same value in the specified column.
User::orderBy('name', 'asc')->get();
Post::orderBy('created_at', 'desc')->get();
Order::groupBy('status')->select('status', DB::raw('count(*) as total'))->get();
This example shows how to get products ordered by price from low to high. Then it groups products by their category and counts how many products are in each category. Finally, it prints both lists.
<?php use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class Product extends Model {} // Get products ordered by price ascending $productsOrdered = Product::orderBy('price', 'asc')->get(); // Group products by category and count them $productsGrouped = Product::groupBy('category')->select('category', DB::raw('count(*) as total'))->get(); // Print results foreach ($productsOrdered as $product) { echo "Product: {$product->name}, Price: {$product->price}\n"; } echo "\nGrouped by category:\n"; foreach ($productsGrouped as $group) { echo "Category: {$group->category}, Count: {$group->total}\n"; }
Always use orderBy before get() to sort results.
When using groupBy, you often need to use select with aggregate functions like count().
Ordering and grouping can be combined for complex queries.
Ordering sorts data by a column in ascending or descending order.
Grouping collects rows with the same value in a column and can be used with counts or sums.
Laravel makes ordering and grouping easy with simple methods on models.