OrderBy does not work with eloquent query builder, how to sort a collection of model instances?

Updated: Jan 28, 2025

OrderBy does not work with eloquent query builder, how to sort a collection of model instances?

OrderBy is actually a method that can be used both on Eloquent query builder results as well as collections of model instances. However, there are some differences in how they are used.

When using OrderBy with Eloquent query builder, you can chain it after the query has been built. For example:

$users = App\User::orderBy('name')->get();

This will execute a SQL query to retrieve all users ordered by name.

However, if you already have a collection of model instances, you cannot use OrderBy in the same way. Instead, you can use the sortBy method provided by Laravel's collection class. Here's an example:

$users = App\User::all();

$sortedUsers = $users->sortBy(function($user) {
    return $user->name;
});

In this example, we first retrieve all users using the all method, which returns a collection of model instances. We then use the sortBy method to sort the collection based on the name property of each user instance. The sortBy method accepts a closure that returns the value to be used for sorting.

Another way to sort a collection of model instances using OrderBy is by converting the collection to an array first, sorting the array using the usort function, and then converting the sorted array back to a collection. Here's an example:

$users = App\User::all()->toArray();

usort($users, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

$sortedUsers = collect($users)->map(function($user) {
    return (object) $user;
});

In this example, we first retrieve all users using the all method and convert the collection to an array using the toArray method. We then use the usort function to sort the array based on the name property of each user. Finally, we convert the sorted array back to a collection using the map method and the object constructor.

Both methods have their pros and cons, and the choice between them depends on the specific use case and performance requirements.