diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 93bf117..9c7ee76 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1174,6 +1174,19 @@ public function take($limit) return $this->slice(0, $limit); } + /** + * Pass the collection to the given callback and then return it. + * + * @param callable $callback + * @return $this + */ + public function tap(callable $callback) + { + $callback(new static($this->items)); + + return $this; + } + /** * Transform each item in the collection using a callback. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 22ac4b3..59be6b0 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1882,6 +1882,19 @@ public function testHigherOrderPartition() $this->assertSame(['b' => ['free' => false]], $premium->toArray()); } + + public function testTap() + { + $collection = new Collection([1, 2, 3]); + + $fromTap = []; + $collection = $collection->tap(function ($collection) use (&$fromTap) { + $fromTap = $collection->slice(0, 1)->toArray(); + }); + + $this->assertSame([1], $fromTap); + $this->assertSame([1, 2, 3], $collection->toArray()); + } } class TestSupportCollectionHigherOrderItem