Laravel collection sortBy not taking effect
10,937
Solution 1
A huge fail on my part, my pretty print JSON chrome extension was messing with the display order, viewing the raw response showed they were in fact sorted correctly... ::facepalm::
Solution 2
To extend on @Titan's answer, i guess the extensions/ postman maintain the array indexing order. Not really sure.
To get rid of that
return $collection->values();
Here is an example
$arr = collect([
0 => [
'name' => 'foo',
'weight' => 70
],
1 => [
'name' => 'bar',
'weight' => 80
]
]);
return $arr->sortByDesc('weight');
the extension will still keep the index order
return $arr->sortByDesc('weight')->values();
This will get the desired order.
Author by
Titan
Updated on June 28, 2022Comments
-
Titan almost 2 years
I'm trying to combine and sort the results from several db queries.
$events = collect(); $downedEvents = EventDowned::where('mission', $missionId) ->orderBy('mission_time', 'asc') ->get(); $events->push($downedEvents); $getInOutEvents = EventGetInOut::where('mission', $missionId) ->orderBy('mission_time', 'asc') ->get(); $events->push($getInOutEvents); $missileEvents = EventMissile::where('mission', $missionId) ->orderBy('mission_time', 'asc') ->get(); $events->push($missileEvents); $flattenedEvents = $events->flatten(); $sortedEvents = $flattenedEvents->sortBy('mission_time'); return $sortedEvents->all();
The result looks like this:
As you can see it has correctly combined the results, however they remain in their original query order, not sorted.
I've also tried
$sortedEvents = $flattenedEvents->sortBy(function($event) { return (int) $event->mission_time; });
-
Shady Atef about 7 yearsI will go back calmly to my AI study., But Good luck that you found it.
-
Traxo about 6 yearsLmao this saved me... Why would it do that!?
-
FeRcHo over 5 years@Titan Really, that was the problem ?, Why do I have exactly the same problem and I have been trying to make the order work for hours and I have not managed any idea or recommendation? please
-
Jicao about 5 yearsI experienced the same issue with Postman... The pretty response was not ordered and the Raw response was ordered like I wanted ! Thanks
-
Merkurial over 4 yearsthis should be marked as correct answer! you saved my day dude!
-
Jonathan Martins about 4 yearsThat is it! 10th time that I've been here. Now its memorized, I promise!
-
Giovanni S almost 3 yearsWas pulling my hair out on this! For anyone reading, "JSON Formatter" for Chrome does this. Thank you!