diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 93bf117c67c3..e9f9e4f9b51a 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -826,6 +826,19 @@ public function pipe(callable $callback) return $callback($this); } + /** + * Pass the collection to the given callback and return the current instance. + * + * @param callable $callback + * @return $this + */ + public function tap(callable $callback) + { + $callback(new static($this->items)); + + return $this; + } + /** * Get and remove the last item from the collection. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 22ac4b3a2599..59be6b0d4290 100755 --- 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