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)) { 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'], ',')); } /**