From d78267d73801f7b3c363e2ae0f01a14a5c89aeb8 Mon Sep 17 00:00:00 2001 From: Brenier Arnaud Date: Tue, 20 Feb 2024 23:27:47 +0100 Subject: [PATCH 1/2] Arr::select not working when $keys is a string Adding a check about $keys type. If it is a string, transform it into an array. If not, it throws a foreach() error --- src/Illuminate/Collections/Arr.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 291d3de39074..9232b3eaf92d 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -516,6 +516,10 @@ public static function only($array, $keys) */ public static function select($array, $keys) { + if (is_string($keys)) { + $keys = [$keys]; + } + return static::map($array, function ($item) use ($keys) { $result = []; From 9509c784376408f5bad60434cd56ab83bea3fd3a Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Wed, 21 Feb 2024 08:17:35 -0600 Subject: [PATCH 2/2] add test --- src/Illuminate/Collections/Arr.php | 4 +--- tests/Support/SupportArrTest.php | 36 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 9232b3eaf92d..e75d87ae979e 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -516,9 +516,7 @@ public static function only($array, $keys) */ public static function select($array, $keys) { - if (is_string($keys)) { - $keys = [$keys]; - } + $keys = static::wrap($keys); return static::map($array, function ($item) use ($keys) { $result = []; diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 05f6b743f3e1..119dd2a3bd65 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -1273,4 +1273,40 @@ public function testTake() 4, 5, 6, ], Arr::take($array, -3)); } + + public function testSelect() + { + $array = [ + [ + 'name' => 'Taylor', + 'role' => 'Developer', + 'age' => 1, + ], + [ + 'name' => 'Abigail', + 'role' => 'Infrastructure', + 'age' => 2, + ], + ]; + + $this->assertEquals([ + [ + 'name' => 'Taylor', + 'age' => 1, + ], + [ + 'name' => 'Abigail', + 'age' => 2, + ], + ], Arr::select($array, ['name', 'age'])); + + $this->assertEquals([ + [ + 'name' => 'Taylor', + ], + [ + 'name' => 'Abigail', + ], + ], Arr::select($array, 'name')); + } }