laravel/framework — pull request #4160 by needbee (2014-04-16 15:51:28+00:00)
Title: modify Collection sort to reset the keys when the array isn't associative

In this fork I fixed (with tests) what I think might be an unintended behavior of the Collection sort methods.

In one of my controllers, I retrieved a Collection via a relationship, then returned it as JSON:

$model = $this->model1->find($id);
return Response::json($model->model2->toArray());

This returned an array:

[{"id":"1", …},{"id":"2", …}, …]

However, a problem occurred when I sorted the Collection:

$model = $this->model1->find($id);
return Response::json($model->model2->sortBy('fieldname')->toArray());

It started returning an object instead:

{"1":{"id":"2", …}, "0":{"id":"1", …}, …}

I noticed that this "object" had integer keys, but not sequential ones. When I var_dump()ed the data to find out what was different, I found out that the objects were still in a Collection, but that not only were the
objects sorted (as intended), but also the array indexes were out of order (which was unintended):

Before:

object(Illuminate\Database\Eloquent\Collection)#317 (1) {
["items":protected]=>
array(16) {
[0]=>
object(…)#300 (28) {…}
[1]=>
object(…)#318 (28) {…}
…
}
}

After:

object(Illuminate\Database\Eloquent\Collection)#317 (1) {
["items":protected]=>
array(16) {
[1]=>
object(…)#318 (28) {…}
[0]=>
object(…)#300 (28) {…}
…
}
}

I noted that this is the result of using associative sort methods. If that behavior is intentional even for non-associative arrays, you can ignore this pull request. But it seems like it might be unintentional, and it leads to the above unexpected behavior with Response::json().

If this behavior is unintentional, this pull request includes new assertions to catch this behavior, and changes to the Collection sort methods to adjust it. If the Collection's array is associative, the associative sorts are still used, but if it is not associative then the non-associative sorts are now used. Using this change, Response::json() still returns an array, just like when unsorted.

Let me know any thoughts, feedback, corrections. Thanks for the review! Hope this is helpful.