Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sortBy() includes keys in the output, but sortByDesc doesn't?

Tags:

php

laravel

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.

like image 530
user2315641 Avatar asked Oct 26 '25 11:10

user2315641


2 Answers

you may use something like this

$collections->sortBy(function ($collection) {
   return $collection->id;
})->values();
like image 196
bhavinjr Avatar answered Oct 29 '25 01:10

bhavinjr


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).

like image 37
Jonas Staudenmeir Avatar answered Oct 29 '25 02:10

Jonas Staudenmeir