What is tap()?
tap() is a helper for “using a value and still returning that same value.” Use it when you want to insert side effects.
The implementation in Illuminate\Support\helpers.php is simple:
tap() ignores the callback’s return value. It always returns the original value.Basic usage
The most basic pattern is: receive a value, run some logic, then return the original value.tap() returns a HigherOrderTapProxy, so you can chain method calls directly.
Common use cases
Insert debug output
Insert logging or event dispatch in the middle of a chain
Trigger side effects without changing the return value
What is the Tappable trait?
If youuse Illuminate\Support\Traits\Tappable, your class gets a tap() method.
tap().
Using it in package development
Tappable is useful when you want to insert side effects into a fluent API chain. When combined with Macroable and Conditionable, you can build highly extensible builder APIs in the Laravel style.
1
Create a fluent class
2
Combine Macroable, Conditionable, and Tappable
Usage in Laravel core
Laravel itself usestap() and Tappable in real code:
Illuminate\Routing\Routeruses bothMacroableandTappableRouter::respondWithRoute()usestap($route)->bind(...)(without a callback), then still returns the original$routeRouter::prepareResponse()usestap(..., fn (...) => event(...))to dispatch an event after response conversionIlluminate\Testing\Fluent\Concerns\Hasimplements assertion helpers with a->tap(...)->first(...)->etc()chain
tap() is a small helper by itself, but when you combine it with Macroable and Conditionable, it becomes much easier to build the readable method chains you often see in Laravel.Next steps
The Macroable trait
Learn how to add custom methods to existing classes.
The Conditionable trait
Learn conditional method chains with
when() and unless().