0
0
Laravelframework~5 mins

Ordering and grouping in Laravel

Choose your learning style9 modes available
Introduction

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.

When you want to show a list of products sorted by price from low to high.
When you need to group users by their roles to see how many users belong to each role.
When displaying blog posts ordered by the newest first.
When summarizing sales data by grouping sales per month.
When filtering and sorting comments by date and grouping them by post.
Syntax
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.

Examples
This gets all users ordered by their name from A to Z.
Laravel
User::orderBy('name', 'asc')->get();
This gets posts ordered by newest first.
Laravel
Post::orderBy('created_at', 'desc')->get();
This groups orders by their status and counts how many orders are in each status.
Laravel
Order::groupBy('status')->select('status', DB::raw('count(*) as total'))->get();
Sample Program

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.

Laravel
<?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";
}
OutputSuccess
Important Notes

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.

Summary

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.