Member-only story
How to Use orderBy() in Laravel Eloquent for Sorting Query Results
2 min readOct 17, 2024
To begin, let’s explore the fundamental use of the orderBy()
method in Laravel Eloquent:
$users = User::query()
->orderBy('name', 'desc')
->get();
In this example, we’re retrieving users from the database and sorting them in descending order based on their names, thanks to the orderBy()
method.
This method takes two parameters:
- The column name to sort by.
- The sort direction, which can be either
asc
(ascending, the default) ordesc
(descending).
Using orderByDesc()
If you only need to sort in descending order, you can opt for the orderByDesc()
method, which is a shorter version of orderBy('column', 'desc')
:
$users = User::query()
->orderByDesc('name')
->get();
This simple adjustment can make your code more concise.
Sorting by Multiple Columns
Need to sort by more than one column? Laravel makes it easy by allowing you to chain multiple orderBy()
calls:
$users = User::query()
->orderBy('name', 'desc')
->orderBy('email', 'asc')
->get();