DEV Community

benittobeny34
benittobeny34

Posted on ā€¢ Originally published at benitto.dev

3 1

Laravel tap helper function

Laravel's tap() is one of the simplest methods in the framework. pass in a value and a a closure , and you'll get back the modified original value. Cleans up code by eliminating temporary variables!

Here are some usage code snippets

-

$user = tap(User::create(['id' => 1, 'name'=> 'raj'])
->sendWelcomeNotification();

//The nice thing about above code is it create the user and sends notification and returns the result of first argument.
Enter fullscreen mode Exit fullscreen mode

-

$user = User::find(1);

$user->update(['name' => 'benitto']);

return $user;

// we can do this in one line

return tap($user)->update(['name'=> 'benitto']);
Enter fullscreen mode Exit fullscreen mode
  • if we pass closure as second arguement the result of first arguement is passed to clousure
$user = tap($user,function($user) {
       $user->sendWelcomeNotification();
       $user->onBoardSetup();
  });
Enter fullscreen mode Exit fullscreen mode

Keep Learning!!

Top comments (0)

Image of Docusign

šŸ› ļø Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more