I'm fetching a collection with relationship and then I try to sort by a column in one of the relationships. The output for using sortBy() is like this:
{
"1": {
"id": 1,
},
"0": {
"id": 2,
}
}
However, when I use sortByDesc() it comes out like this:
[
{
"id": 2,
},
{
"id": 1,
}
]
Is there a reason for this? It doesn't present a problem if I use it inside a Controller or View, however it is used as output in an AJAX call and breaks everything. Is there a way to have consistent output? sortByDesc() output works best for me since I don't need keys.
you may use something like this
$collections->sortBy(function ($collection) {
return $collection->id;
})->values();
sortBy() and sortByDesc() behave the same way, the difference is your data.
If the sorted result has consecutive integer keys (0, 1, 2), json_encode() will return an array (your second case). Otherwise, json_encode() will return an object (your first case).
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