'Natural ORDER in Laravel Eloquent ORM
How can i get 'natural order' in 'Eloquent ORM'? In table I have column 'text' (string).
Normal order: Model::orderBy('text')
'value 1'
'value 12'
'value 23'
'value 3'
'value 8'
I need this:
'value 1'
'value 3'
'value 8'
'value 12'
'value 23'
Any ideas?
Solution 1:[1]
You could add a raw query and do something like this:
Model::orderBy(DB::raw('LENGTH(text), text'));
Or, in modern versions of Laravel:
Model::orderByRaw('LENGTH(text), text');
Solution 2:[2]
For Laravel this also works:
$collection = $collection->sortBy('order', SORT_NATURAL, true);
Solution 3:[3]
Sort collection (SORT_NATURAL):
FROM
1 => "...\src\storage\avatars\10.jpg"
0 => "...\src\storage\avatars\1.jpg"
2 => "...\src\storage\avatars\100.jpg"
3 => "...\src\storage\avatars\1000.jpg"
4 => "...\src\storage\avatars\101.jpg"
5 => "...\src\storage\avatars\102.jpg"
TO
0 => "...\src\storage\avatars\1.jpg"
1 => "...\src\storage\avatars\10.jpg"
2 => "...\src\storage\avatars\100.jpg"
3 => "...\src\storage\avatars\101.jpg"
4 => "...\src\storage\avatars\102.jpg"
5 => "...\src\storage\avatars\1000.jpg"
$natsort_collection = $collection->sortBy(null, SORT_NATURAL)->values();
// If you work with arrays:
sort(...array of your data here..., SORT_NATURAL);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | miken32 |
Solution 2 | Erhnam |
Solution 3 |