diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 4a54ea0abc2f..ac8f991a9e3c 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1890,6 +1890,28 @@ public function count() return count($this->items); } + /** + * Count the number of items in the collection by some predicate. + * + * @param callable|null + * @return static + */ + public function countBy($predicate = null) + { + if (is_null($predicate)) { + $predicate = function ($val) { + return $val; + }; + } + + return new static( + $this->groupBy($predicate) + ->map(function ($val) { + return $val->count(); + }) + ); + } + /** * Add an item to the collection. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index e6cf19855751..2728396c4aaa 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -307,6 +307,31 @@ public function testCountable() $this->assertCount(2, $c); } + public function testCountableByWithoutPredicate() + { + $c = new Collection(['foo', 'foo', 'foo', 'bar', 'bar', 'foobar']); + $this->assertEquals(['foo' => 3, 'bar' => 2, 'foobar' => 1], $c->countBy()->all()); + + $c = new Collection([true, true, false, false, false]); + $this->assertEquals([true => 2, false => 3], $c->countBy()->all()); + + $c = new Collection([1, 5, 1, 5, 5, 1]); + $this->assertEquals([1 => 3, 5 => 3], $c->countBy()->all()); + } + + public function testCountableByWithPredicate() + { + $c = new Collection(['alice', 'aaron', 'bob', 'carla']); + $this->assertEquals(['a' => 2, 'b' => 1, 'c' => 1], $c->countBy(function ($name) { + return substr($name, 0, 1); + })->all()); + + $c = new Collection([1, 2, 3, 4, 5]); + $this->assertEquals([true => 2, false => 3], $c->countBy(function ($i) { + return $i % 2 === 0; + })->all()); + } + public function testIterable() { $c = new Collection(['foo']);