The tap() Helper for Fluent Code
December 09, 2025
•
1 min read
•
116 views
Table of Contents
The tap() helper allows you to perform operations on an object and return the object itself:
Without tap()
$user = User::create($request->validated());
$user->assignRole('member');
$user->sendWelcomeEmail();
return $user;
With tap()
return tap(User::create($request->validated()), function ($user) {
$user->assignRole('member');
$user->sendWelcomeEmail();
});
Even Shorter with Arrow Functions
return tap(User::create($request->validated()))
->assignRole('member')
->sendWelcomeEmail();
This is especially useful when you want to update and return a model in one line:
return tap($user)->update(['last_login' => now()]);
Related Posts
Laravel Sanctum API Authentication Complete Guide
Build secure API authentication with Laravel Sanctum for SPAs and mobile apps.
Laravel Rate Limiting: Protect Your Application
Implement rate limiting to protect your Laravel application from abuse.
Laravel Blade Components: Build Reusable UI
Create powerful reusable components with Laravel Blade.
Comments (0)
No comments yet. Be the first to comment!