Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

Hello folks,

Is there a way to coerce an orderBy clause in to return the field sorted in a natural order? I could always offload the sorting after the query using PHP's natsort function, but would lose the benefit of skip and limit clauses on the resulting query (i.e., I would need to implement the effects of skip and limit in PHP as well, losing much efficiency for big relations).

I have seen some suggestions to do something like orderByRaw('LENGTH(field), field'), but this doesn't work in my case: the contents of field are alphanumeric and aren't all like Product 1, Product 2, etc. There are other entries like Object with a really long name that should appear before all Product x, but wouldn't with the above solution.

I'd like to do something like:

Model::all()->orderByNat('field')->skip(100)->limit(10)

Any other ideas? Thanks!

Last updated 3 years ago.
0

A tough one - might get better responses on a mysql forum...

SELECT field+0<>0, field+0, field FROM `table`  ORDER BY field+0<>0 DESC, field+0, field; 
0

When I needed to do something similar in the past I just stuck in an extra field for sorting. When a record is saved parse the string and left pad all numbers to 6? digits with zeros. save that in the sort field and job done.

0

Thanks @kpzani; that's what I ended up doing. Not the cleanest, but it gets the job done!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.