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');
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With