Skip to content

Commit

Permalink
[9.x] Added callback support on implode Collection method. (#41405)
Browse files Browse the repository at this point in the history
* [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
<span>{{ $user->cities->map(fn ($city) => $city->name.' ('.$city->state->name.')')->implode(', ') }}</span>
```

After:

```php
<span>{{ $user->cities->implode(fn ($city) => $city->name.' ('.$city->state->name.')', ', ') }}</span>
```

* Added implode callback test
  • Loading branch information
eusonlito committed Mar 9, 2022
1 parent cf29656 commit 1208f45
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Illuminate/Collections/Collection.php
Expand Up @@ -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)) {
Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -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'], ','));
}

/**
Expand Down

0 comments on commit 1208f45

Please sign in to comment.