Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural ORDER in Eloquent ORM, Laravel 4

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?

like image 662
Lajdák Marek Avatar asked Jul 17 '13 00:07

Lajdák Marek


2 Answers

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');
like image 68
Laurence Avatar answered Oct 27 '22 18:10

Laurence


For Laravel this also works:

$collection = $collection->sortBy('order', SORT_NATURAL, true);
like image 31
Erhnam Avatar answered Oct 27 '22 16:10

Erhnam