
Laravel Eloquent: sort query results using orderBy()
Laravel orderBy() basics
When you need to sort data in Laravel, the Laravel order by methods give you everything you need—no raw SQL, no drama. Here’s the foundation of the orderBy()
method:
$users = User::query() ->orderBy('name', 'desc') ->get();
In this snippet, we’re using Laravel Eloquent to fetch users from their table and ordering them in descending order by their names thanks to the orderBy()
method.
Its parameters are:
- The column’s name.
- The order direction: Either
asc
(the default value) for ascending ordesc
for descending.
See the official docs for ordering queries.
The orderByDesc() method
If you want to sort your results in descending order, you can also use the orderByDesc()
method, which is a shortcut for orderBy('column', 'desc')
:
$users = User::query() ->orderByDesc('name') ->get();
It’s all in the details!
Multi-column sorting using orderBy()
What if you want to sort by multiple columns? Simple. Just chain multiple orderBy()
methods:
$users = User::query() ->orderBy('name', 'desc') ->orderBy('email', 'asc') ->get();
This way, Eloquent sorts users by their names first. If two or more users have the same name, it then sorts those users by their email in ascending order.
I actually learned that only after years of SQL and Laravel experience.
Getting fancy with orderByRaw()
When you need a more complex sorting mechanism, Laravel’s got you covered with orderByRaw()
:
$orders = User::query() ->orderByRaw('updated_at - created_at DESC') ->get();
This advanced method lets you sort the results based on the difference between the updated_at
and created_at
timestamps. Handy, right?
If you need to use user input, always use bindings to prevent SQL injection:
$query->orderByRaw('some_column > ?', [$value]);
See the official docs for raw orderings.
Heads-up:
updated_at - created_at
works in MySQL and Postgres, but not in SQL Server. On SQL Server, useDATEDIFF(SECOND, created_at, updated_at)
.
Use reorder() to unorder what’s already been ordered
If you need to undo the ordering of a query you are building based on some condition, you can use the reorder()
method:
$ordered = User::query()->orderBy('name'); $unordered = $ordered->reorder()->get();
And if you wish to reset and apply a completely new ordering without calling orderBy()
again:
$ordered = User::query()->orderBy('name'); $reorderedByEmail = $ordered->reorder('email', 'desc')->get();
I’ll never get bored of Laravel’s convenience! Docs: Removing existing orderings
See also:
latest()
/oldest()
: terser helpers that default tocreated_at
but can take any column.inRandomOrder()
: for that random “featured” user or contest winner logic.
Did you like this article? Then, keep learning:
- Fix common Laravel SQL transactional error related to SAVEPOINTs during queries
- Understand and fix the "419 Page Expired" error often related to session timeout
- Learn asynchronous caching techniques for Laravel database queries
- Learn how to clear Laravel caches which can affect query results
- Master error handling in Laravel's HTTP client for robust apps
- Learn about Laravel's query builder reorder() in complex ordering cases
- Understand Laravel's maintenance mode for app downtime management
- Deepen your Laravel query skills with flexible 'where' clauses
- Efficient filtering in Laravel queries using whereIn() method
0 comments