kay899's avatar

How can I natsort my data?

Hi,

I have some data for a SelectBox which I need to be sorted naturally.

With orderBy I got 1.01, 10.01, 2.01 but I'll need 1.01, 2.01, 10.01

Is there a way I can use natsort with Laravel.

My actual code is:

public function episodes()
{
    return $this->hasMany('Episode')->orderBy('serial_no');
}

If there is no real solution, my idea is to have a second function like orderByNat with returns the data with return natsort($this);

How could I extend this, if there is no better option?

Thanks Andreas

0 likes
7 replies
MarkRedeman's avatar

Given that you're sorting episodes, couldn't you just sort on release date instead of a serial number?

I don't think it will be easy to implement a natsort method for Eloquent as it will be dependent on the database that's used.

kay899's avatar

I don't see that option actually.

I store these serial numbers as varchar in DB: 1.01, 2.20 etc.

bestmomo's avatar
Level 52

Maybe something like this :

public function episodes()
{
    return $this->hasMany('Episode')->orderBy(DB::raw('LENGTH(serial_no), serial_no'));
}

Never tried that ^^

3 likes
kay899's avatar

Thanks bestmomo Solved it with that code...

MartelliEnrico's avatar

The best solution is probably to use the sort(callable $callback) method inside the Collection class. Just call the method ->sort('natsort') once you got the Eloquent Collection (normally after the ->get() call).

BelleAme2917's avatar

It is working for me: Create a helper class SortHelper and use it whereever you want.

Note: $myItemsArray should be type of -> Illuminate\Support\Collection

Usage: $items = SortHelper::alphaNumericSort($myItemsArray, 'code');

SortHelper:


namespace App\Helpers;

use Illuminate\Support\Collection;

class SortHelper
{
    public static function alphaNumericSort($items, $column)
    {
        if (!($items instanceof Collection)) {
            return $items;
        }

        return $items->sortBy(function ($item) use ($column) {
            $value = $item->$column;

            if (is_numeric($value)) {
                return sprintf('%012d', $value);
            } else {
                return $value;
            }
        });
    }
}```

Please or to participate in this conversation.