From 7094bc17f6cc9fe64d47d5ab4e10f576de85fe24 Mon Sep 17 00:00:00 2001 From: Arthur Perton Date: Tue, 9 Aug 2022 15:26:41 +0200 Subject: [PATCH] Keep original keys when using Collection->sortBy() with an array of sort operations (#43609) * Add test * Use usaort instead of usort to keep the original keys --- src/Illuminate/Collections/Collection.php | 2 +- tests/Support/SupportCollectionTest.php | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index e311fa773b54..62aa1d430cf4 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -1366,7 +1366,7 @@ protected function sortByMany(array $comparisons = []) { $items = $this->items; - usort($items, function ($a, $b) use ($comparisons) { + uasort($items, function ($a, $b) use ($comparisons) { foreach ($comparisons as $comparison) { $comparison = Arr::wrap($comparison); diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 51e51c76dc05..2d0cab7eefb8 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1982,6 +1982,16 @@ public function testSortByAlwaysReturnsAssoc($collection) }); $this->assertEquals([1 => 'dayle', 0 => 'taylor'], $data->all()); + + $data = new $collection(['a' => ['sort' => 2], 'b' => ['sort' => 1]]); + $data = $data->sortBy([['sort', 'asc']]); + + $this->assertEquals(['b' => ['sort' => 1], 'a' => ['sort' => 2]], $data->all()); + + $data = new $collection([['sort' => 2], ['sort' => 1]]); + $data = $data->sortBy([['sort', 'asc']]); + + $this->assertEquals([1 => ['sort' => 1], 0 => ['sort' => 2]], $data->all()); } /**