3

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.

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.