Skip to content

Commit

Permalink
[10.x] Fix for sortByDesc ignoring multiple attributes (#50431)
Browse files Browse the repository at this point in the history
* Failing Test

* Fix for sortByDesc

* Update Collection.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
TWithers and taylorotwell committed Mar 10, 2024
1 parent f2bff1c commit 24d7bd2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1490,6 +1490,16 @@ protected function sortByMany(array $comparisons = [], int $options = SORT_REGUL
*/
public function sortByDesc($callback, $options = SORT_REGULAR)
{
if (is_array($callback) && ! is_callable($callback)) {
foreach ($callback as $index => $key) {
$comparison = Arr::wrap($key);

$comparison[1] = 'desc';

$callback[$index] = $comparison;
}
}

return $this->sortBy($callback, $options, true);
}

Expand Down
15 changes: 15 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2047,6 +2047,21 @@ public function testSortByCallableString($collection)
$this->assertEquals([['sort' => 1], ['sort' => 2]], array_values($data->all()));
}

#[DataProvider('collectionClassProvider')]
public function testSortByCallableStringDesc($collection)
{
$data = new $collection([['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]);
$data = $data->sortByDesc(['id']);
$this->assertEquals([['id' => 2, 'name' => 'bar'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));

$data = new $collection([['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar'], ['id' => 2, 'name' => 'baz']]);
$data = $data->sortByDesc(['id']);
$this->assertEquals([['id' => 2, 'name' => 'bar'], ['id' => 2, 'name' => 'baz'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));

$data = $data->sortByDesc(['id', 'name']);
$this->assertEquals([['id' => 2, 'name' => 'baz'], ['id' => 2, 'name' => 'bar'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit 24d7bd2

Please sign in to comment.