0
0
LaravelHow-ToBeginner · 3 min read

How to Use orderBy in Eloquent: Laravel Query Sorting

In Laravel Eloquent, use the orderBy method to sort query results by a specific column. You can specify the column name and the direction (asc or desc) to control the sorting order.
📐

Syntax

The orderBy method accepts two parameters: the column name to sort by, and the direction of sorting which can be either asc for ascending or desc for descending order. The direction parameter is optional and defaults to asc.

php
Model::orderBy('column_name', 'asc')->get();
💻

Example

This example shows how to retrieve all users sorted by their created_at date in descending order, so the newest users appear first.

php
<?php
use App\Models\User;

$users = User::orderBy('created_at', 'desc')->get();

foreach ($users as $user) {
    echo $user->name . ' - ' . $user->created_at . "\n";
}
Output
Alice - 2024-06-10 14:23:45 Bob - 2024-05-20 09:15:30 Charlie - 2024-04-01 18:00:00
⚠️

Common Pitfalls

  • Forgetting to specify the direction defaults to ascending order, which might not be what you want.
  • Using orderBy after get() will cause an error because get() executes the query immediately.
  • Chaining multiple orderBy calls is allowed to sort by multiple columns.
php
<?php
// Wrong: calling get() before orderBy
$users = User::get()->orderBy('name'); // This will cause an error

// Right: orderBy before get
$users = User::orderBy('name')->get();
📊

Quick Reference

UsageDescription
orderBy('column')Sort by column ascending (default)
orderBy('column', 'desc')Sort by column descending
orderBy('col1')->orderBy('col2', 'desc')Sort by multiple columns
Model::orderBy(...)->get()Execute sorted query and get results

Key Takeaways

Use orderBy before get() to sort query results in Eloquent.
Specify 'asc' or 'desc' to control sorting direction; 'asc' is default.
You can chain multiple orderBy calls to sort by multiple columns.
Calling orderBy after get() causes errors because the query is already executed.
orderBy helps organize data for better readability and user experience.