From a77f1b6b5bd19ae32054d7921da21fcee5cb328b Mon Sep 17 00:00:00 2001 From: Lito Date: Wed, 9 Mar 2022 12:58:06 +0100 Subject: [PATCH 1/2] [9.x] Added callback support on implode Collection method. Allow to use a callback as `$value` on `implode` Collection method to simplify -`>map()->implode()` calls: Before: ```php {{ $user->cities->map(fn ($city) => $city->name.' ('.$city->state->name.')')->implode(', ') }} ``` After: ```php {{ $user->cities->implode(fn ($city) => $city->name.' ('.$city->state->name.')', ', ') }} ``` --- src/Illuminate/Collections/Collection.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 907016d4b506..b8ba7a1aef87 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -577,12 +577,16 @@ public function hasAny($key) /** * Concatenate values of a given key as a string. * - * @param string $value + * @param callable|string $value * @param string|null $glue * @return string */ public function implode($value, $glue = null) { + if (is_callable($value)) { + return implode($glue ?? '', $this->map($value)->all()); + } + $first = $this->first(); if (is_array($first) || (is_object($first) && ! $first instanceof Stringable)) { From 4994d3b448af2c98031defeae9f29fb79ec5816f Mon Sep 17 00:00:00 2001 From: Lito Date: Wed, 9 Mar 2022 13:00:11 +0100 Subject: [PATCH 2/2] Added implode callback test --- tests/Support/SupportCollectionTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 49f2cf1ee574..f8263ed78010 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2136,6 +2136,10 @@ public function testImplode($collection) $data = new $collection([Str::of('taylor'), Str::of('dayle')]); $this->assertSame('taylordayle', $data->implode('')); $this->assertSame('taylor,dayle', $data->implode(',')); + + $data = new $collection([['name' => 'taylor', 'email' => 'foo'], ['name' => 'dayle', 'email' => 'bar']]); + $this->assertSame('taylor-foodayle-bar', $data->implode(fn ($user) => $user['name'].'-'.$user['email'])); + $this->assertSame('taylor-foo,dayle-bar', $data->implode(fn ($user) => $user['name'].'-'.$user['email'], ',')); } /**