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().

The Problem :-

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.

The Solution: Dynamic Method Call

Laravel provides two separate methods for sorting:

  • sortBy() → ascending
  • sortByDesc() → descending

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.

Example :-

$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;
});

Quick Tips :-

  • Use orderBy() if you’re sorting directly in the database — it’s more performant.
  • Use sortBy() OR sortByDesc() only when working with in-memory Eloquent collections.
  • Dynamic method calls are a clean way to toggle sort direction based on user input or business logic.

Conclusion :-

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.

Need Help With Laravel Development?

Work with our skilled Laravel developers to accelerate your project and boost its performance.

Hire Laravel Developer

Support On Demand!

Related Q&A