Skip to content

Commit edc6398

Browse files
jerguslejkotaylorotwell
authored andcommitted
Add 'filter by attribute' functionality (#21898)
1 parent f17e12f commit edc6398

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/Illuminate/Support/Collection.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,11 +408,15 @@ public function except($keys)
408408
/**
409409
* Run a filter over each of the items.
410410
*
411-
* @param callable|null $callback
411+
* @param mixed|null $callback
412412
* @return static
413413
*/
414-
public function filter(callable $callback = null)
414+
public function filter($callback = null)
415415
{
416+
if (is_string($callback)) {
417+
$callback = $this->valueRetriever($callback);
418+
}
419+
416420
if ($callback) {
417421
return new static(Arr::where($this->items, $callback));
418422
}

tests/Support/SupportCollectionTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,13 @@ public function testFilter()
305305
$this->assertEquals(['first' => 'Hello', 'second' => 'World'], $c->filter(function ($item, $key) {
306306
return $key != 'id';
307307
})->all());
308+
309+
$c = new Collection([
310+
['value' => 'foo', 'nested' => ['included' => true]],
311+
['value' => 'bar', 'nested' => ['included' => false]],
312+
['value' => 'baz', 'nested' => ['included' => true]],
313+
]);
314+
$this->assertEquals(['foo', 'baz'], $c->filter('nested.included')->pluck('value')->toArray());
308315
}
309316

310317
public function testHigherOrderKeyBy()

0 commit comments

Comments
 (0)