DEV Community

benittobeny34
benittobeny34

Posted on • Originally published at benitto.dev

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)