The tap() Helper
Call a closure on a value and return the value, not the closure result. Perfect for chaining side-effects without breaking a fluent chain.
Overview
The tap() helper calls a closure with a given value, then returns the value itself — not whatever the closure returns. This is incredibly useful for performing side-effects in the middle of a chain.
Usage
return tap(User::find(1), function (User $user) {
$user->update(['last_login_at' => now()]);
});
You can also use it with the higher-order tap proxy:
return tap(User::find(1))->update(['last_login_at' => now()]);
When to Use
- Performing side-effects (logging, events) in the middle of a return statement
- Updating a model and returning it in one expression
- Avoiding temporary variables that clutter your code