19

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');
}
1
  • Looks fine. Could you post any other relevant code. Commented Jun 8, 2015 at 20:04

2 Answers 2

42

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

4 years later I can't believe this is not called automatically when you're returning a Collection as a response, and it's so hard to find the right keywords for this answer!
Still valid answer in Laravel 8 when you use sortBy('') items remains with their original keys while their reallocated already and this may cause chaos on displaying so to get rid of keys sortBy('attribute')->values() will return only sorted items.
2

If you want to get rid of numerical keys you should use:

return \Location::all(['locationId', 'name'])->sortBy('name')->values()->all();

Reference - sortBy

1 Comment

Adding the all() method will return an array of the underlying items, not the Collection object. The original function returned the Collection, so I would assume this return type should not be changed.

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.