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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay