In Laravel, sorting data is straightforward when you’re working with query builders using orderBy(). But what happens when you’re dealing with Eloquent collections?
Collections are often used after fetching data with ->get(), or when you’ve already loaded relationships. In those cases, sorting happens in memory, and you must use collection methods like sortBy() or sortByDesc().
Let’s say you have a collection of users and want to sort them by name. You might try:
$users->sortBy('name', SORT_DESC); // Incorrect
This doesn’t work the way you expect because Laravel’s sortBy() method doesn’t accept a sort direction like SORT_DESC in the same way native PHP does.
Laravel provides two separate methods for sorting:
To dynamically choose between them, you can do this:
$sorted = $collection->{$direction === 'asc' ? 'sortBy' : 'sortByDesc'}('field_name');
This simple one-liner evaluates the direction and uses the appropriate method.
$users = User::all(); // This returns a collection
$direction = request('sort', 'asc'); // Get sort direction from request, default to 'asc'
$sortedUsers = $users->{$direction === 'asc' ? 'sortBy' : 'sortByDesc'}('name');
// You can now loop over $sortedUsers in your Blade template or return it from an API response.
Sorting by Nested or Custom Attributes :-
Need to sort by something more complex, like a nested relationship or computed value?
Use a callback:
$sorted = $collection->{$direction === 'asc' ? 'sortBy' : 'sortByDesc'}(function ($item) {
return $item->profile->last_name;
});
Laravel makes working with collections elegant, but it’s important to know that sortBy() doesn’t accept a direction argument. Instead, dynamically switch between sortBy() and sortByDesc() using the ternary operator or conditional logic.
This small technique can cleanly handle dynamic sorting needs without writing repetitive code — making your Laravel apps smarter and cleaner.
Work with our skilled Laravel developers to accelerate your project and boost its performance.
Hire Laravel Developer