From 03992ea27c44e3b89f444451171fcda1b4cea168 Mon Sep 17 00:00:00 2001 From: Jeremias Wolff Date: Tue, 27 May 2025 21:34:11 +0200 Subject: [PATCH 1/2] fix bug: enhance handling of empty values in grouping --- src/Illuminate/Collections/Collection.php | 8 ++++--- tests/Support/SupportCollectionTest.php | 26 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 95faa17a7121..a1467f8ec7ee 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -516,9 +516,11 @@ public function groupBy($groupBy, $preserveKeys = false) foreach ($this->items as $key => $value) { $groupKeys = $groupBy($value, $key); - if (! is_array($groupKeys)) { - $groupKeys = [$groupKeys]; - } + $groupKeys = match (true) { + ! is_array($groupKeys) => [$groupKeys], + is_array($groupKeys) && empty($groupKeys) => [null], + default => $groupKeys, + }; foreach ($groupKeys as $groupKey) { $groupKey = match (true) { diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 513e1fa4187a..19ab7e02338b 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -3457,6 +3457,32 @@ function ($item) { $this->assertEquals($expected_result, $result->toArray()); } + #[DataProvider('collectionClassProvider')] + public function testGroupWithEmptyValue($collection) + { + $data = new $collection([ + 10 => [], + 20 => ['user' => 2, 'roles' => []], + 30 => ['user' => 3, 'roles' => [null]], + 40 => ['user' => 4, 'roles' => ['Role_2']], + ]); + + $result = $data->groupBy('roles', true); + + $expected_result = [ + '' => [ + 10 => [], + 20 => ['user' => 2, 'roles' => []], + 30 => ['user' => 3, 'roles' => [null]], + ], + 'Role_2' => [ + 40 => ['user' => 4, 'roles' => ['Role_2']], + ], + ]; + + $this->assertEquals($expected_result, $result->toArray()); + } + #[DataProvider('collectionClassProvider')] public function testKeyByAttribute($collection) { From 629f605b7f310e8b6d31b29152f36848792ce8eb Mon Sep 17 00:00:00 2001 From: Jeremias Wolff Date: Wed, 28 May 2025 19:48:27 +0200 Subject: [PATCH 2/2] style ci --- src/Illuminate/Collections/Collection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index a1467f8ec7ee..cccbf2e3efd8 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -520,7 +520,7 @@ public function groupBy($groupBy, $preserveKeys = false) ! is_array($groupKeys) => [$groupKeys], is_array($groupKeys) && empty($groupKeys) => [null], default => $groupKeys, - }; + }; foreach ($groupKeys as $groupKey) { $groupKey = match (true) {