Search code examples
laraveldatabasesortingcollections

sorting a collection with a 'double' column


I tried to sort a collection, that has a column named 'filesize'. It is a decimal column, and I've set that in the migration since I want a comma separator in the database, for the column 'filesize'.

But somehow laravel doesn't want to sort the database collection on 'filesize', from the items that I loaded from the db.

The sorting function works however, when I sort on another column. The column 'width' is set to string, and it sorts that column without any problems.

This is the code I used for this example:

$duplis->sortby('filesize', 1);

I also tried this example, because it is a nested collection that I want to sort:

$sorted = $duplis->sortBy(function ($item) {
    //dd($item);
    return $item->filesize;
 }, 3);

I hope someone could help.

Thanks!


Solution

  • Based on your screenshot, we know that $duplis is a collection of key-value pairs, whose:

    • keys are numeric (i.e., 4665 in your screenshot), and
    • values are sub-collections that contain the Orders that need to be sorted.

    Given this information, if you want to have a collection of sorted Orders, extracted from $duplis, then do:

    $sorted = $duplis->map(function ($orders) {
        return $orders->sortBy('filesize');
    });