Laravel’s tap() helper

Laravel’s tap() is global helper function , that is used for improving the Laravel framework’s declarative capabilities.Tap() function is inspired from Ruby.Tap() simply takes $value and a $callback / anonymous function. The $callback will execute with the $value as the argument. And finally the $value will be returned.You can make changes in value in callback. Here is the basic implementation of the function:
function tap($value, $callback)
{
$callback($value);
return $value;
}

Below is a simple implementation of Tap() function for modifying an collection.

public function updateUserEmail(Request $request){
$user_id=Auth::id();
$email_id= $request->input('email');

return tap(User::find($user_id), function ($instance) use ($email_id){
$instance->email=$email_id;
$instance->save();
});
}


In above example we have used tap helper to update the email address of logged in User.

Leave a Reply

Your email address will not be published. Required fields are marked *