How to sort in laravel eloquent?

Viewed 416

When i sort it gives me data like this:

10
19
100
20
abc
fff

How can i properly sort it like this:

10
19
20
100
abc
fff

Model::orderBy('text','asc')->get();
4 Answers

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys :

$q = Model::orderBy('text','asc')->get();
$sorted = $q->sortBy('text');

Alternatively, you can use sortByDesc() method. sortDesc() method will sort the collection in the opposite order as the sort() method.

you need to declare the field in your table as an Integer and not as a String. If a field is of String type its values are evaluated like this: "100" < "20" But if the field is of Integer type, eloquent evaluate like this: 20 < 100 Hi.

You can also use sortBy to sort your data with passing closer to your query, have added an example you can use it.

class::all()->sortBy(function ($query){
   return $query->Your_Field_Name;
});

It will also depend on what data type you have chosen in your migration.

you can sort based on the column if it can be casted to UNSIGNED number, otherwise sort by the column it self:

 Model::orderByRaw('CAST(text AS UNSIGNED), text')->get();
Related