What is tap() helper in Laravel?
Answer
The tap() helper passes a value to a callback and then returns the original value. It is designed for performing side effects without interrupting a chain. Example: return tap(User::create($data), fn($user) => $user->sendWelcomeEmail()) — creates the user, sends the email (side effect), and returns the user. Without tap: $user = User::create($data); $user->sendWelcomeEmail(); return $user;. In Eloquent: $user->tap(fn() => event(new UserSaved($user)))->save(). Tap is also used for debugging in method chains: User::where("active", true)->tap(fn($q) => info($q->toSql()))->paginate(). The $this->tap() shorthand in models: return $model->tap->sendWelcomeEmail(). Tap encourages side effects to be named and explicit rather than hidden inside the main expression.
Previous
What is the when() method in Laravel Query Builder?
Next
What are Eloquent eager loading with constraints?