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.

Share:
10,937
Titan
Author by

Titan

Updated on June 28, 2022

Comments

  • Titan
    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:

    ss

    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
    Shady Atef about 7 years
    I will go back calmly to my AI study., But Good luck that you found it.
  • Traxo
    Traxo about 6 years
    Lmao this saved me... Why would it do that!?
  • FeRcHo
    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
    Jicao about 5 years
    I experienced the same issue with Postman... The pretty response was not ordered and the Raw response was ordered like I wanted ! Thanks
  • Merkurial
    Merkurial over 4 years
    this should be marked as correct answer! you saved my day dude!
  • Jonathan Martins
    Jonathan Martins about 4 years
    That is it! 10th time that I've been here. Now its memorized, I promise!
  • Giovanni S
    Giovanni S almost 3 years
    Was pulling my hair out on this! For anyone reading, "JSON Formatter" for Chrome does this. Thank you!