2

I don't know what causes the problem, but below is the original PHP code which resulted with the wanted JSON format:

PHP

return response()->json($model->things, 200);

JSON

[
    {...},
    {...},
    ...
]

However, when I sorted the collection, the array in JSON became an object.

PHP

return response()->json($model->things->sortBy("name"), 200);

JSON

{
    "0": {...},
    "1": {...},
    ...
}

Did I do something wrong? I tried dding the collection in the 2 cases, but the results look the same to me.

Daniel Cheung
  • 4,258
  • 1
  • 25
  • 54

1 Answers1

9

From laravel documentation:

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys

so after sortBy() you have something like this:

[2=>'val1', 1 => 'val2', 0 => 'val3']

and it's associative array, and that explains why in json it became an object, and to prevent this you need to use values() method like this:

$model->things->sortBy("name")->values()->all()

second question is why it is not sorted, and you can read this question: json_encode not preserving order

RainDev
  • 1,033
  • 6
  • 8