Laravel tap() Helper
Laravel Hidden Gem: tap() Helper
Sometimes, you want to perform an action on an object and still return the same object. Laravel’s tap() helper makes this super easy!
Normally, you might write:
$user = User::find(1);
$user->update(['active' => true]);
return $user;
With tap(), it’s cleaner:
$user = tap(User::find(1), function ($user) {
$user->update(['active' => true]);
});
You can even chain it:
return tap(User::find(1))
->update(['active' => true]);
- Saves lines of code
- Keeps logic tidy
- Perfect for quick updates + returning the same model