OrderBy does not work with eloquent query builder, how can I sort a collection of models using eloquent?
OrderBy is actually a method that is available in Eloquent query builder, not just in raw SQL queries. However, if you have already executed a query and have a collection of models in hand, you cannot use OrderBy directly on that collection. Instead, you can use the sortBy
method provided by Laravel's collection processing functions.
Here's an example of how to sort a collection of models using Eloquent:
// Execute the query and get the collection of models
$models = App\Model::all();
// Sort the collection based on a specific column and in ascending order
$sortedModels = $models->sortBy('column_name');
// If you want to sort in descending order, use the `desc` method instead
$sortedModels = $models->sortByDesc('column_name');
In the above example, replace App\Model
with the name of your model class, and column_name
with the name of the column you want to sort by. The sortBy
method sorts the collection based on the specified column, and returns a new collection with the sorted models.
If you want to apply other filtering or sorting conditions to the query before getting the collection, you can chain multiple methods together in the query builder itself, and then use the get()
method to get the collection. For example:
// Execute the query and get the collection of models
$models = App\Model::where('column1', 'value1')
->orderBy('column2', 'desc')
->get();
In the above example, the query is filtered based on the value of column1
, and sorted in descending order based on the value of column2
. The get()
method is used to execute the query and get the collection of models.