Laravel/ PHP: Order By Alphabetical with numbers in order

It might be late but for others it might help.

Based on above link I found below, I derived the best way that would likely solve your problem with the example code: https://www.electrictoolbox.com/mysql-order-string-as-int/

Query

SELECT * FROM <table> ORDER BY CAST(<column> AS unsigned)

Example for laravel

DB::table('test')
    ->orderByRaw("CAST(title as UNSIGNED) ASC")
    ->get();

You are being posed with the problem of sorting items alphanumerically, or in computer science terms, natural sorting.

There are many ways to achieve a natural sort with straight MySQL but you could also take the results from your Laravel helper into array format and implement PHP's natsort function instead.

From the methods I found above, I derived the best way that would likely solve your problem with the example code:

DB::table('test')->orderBy('LENGTH(title)', 'ASC')
    ->orderBy('title', 'ASC')
    ->get();

however I'm not sure if the helper will complain about receiving a MySQL function instead of a straight column name into the orderBy function. I'm only transcribing from the references I used in combination with your example too - I cannot guarantee the efficacy.


For Laravel this also works:

$collection = $collection->sortBy('order', SORT_REGULAR, true);

Tags:

Mysql

Php

Laravel