Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Sorted collection output is not an array

I'm trying to sort a collection by the column name. I am logging the ajax result and when I sort by name I get:

Object: {0: Object, 1: Object, ...}

But when I sort by the other field (locationId) I get:

[Object, Object, ...]

Any idea what I'm doing wrong? I need the result in an array like when I sort by locationId.

public function getLocations()
{
    return \Location::all(['locationId', 'name'])->sortBy('name');
}
like image 538
jstudios Avatar asked Jun 08 '15 19:06

jstudios


1 Answers

When you sort by locationId, the keys for the items don't change, since the items were sorted that way already. For example, the keys would stay 0, 1, 2, etc., which is a valid indexed array.

However, when you sort by the name field, the keys will move around with the item they reference. So, your keys may end up like 0, 2, 1, etc. Since this order of keys is not a valid indexed array, it is treated as an associative array, which is translated into an object in json.

You just need to rekey the items array after the sort. The Collection has a values() method to do this.

public function getLocations()
{
    return \Location::all(['locationId', 'name'])->sortBy('name')->values();
}
like image 71
patricus Avatar answered Oct 05 '22 19:10

patricus