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.
-
$user = User::find(1);
$user->update(['name' => 'benitto']);
return $user;
// we can do this in one line
return tap($user)->update(['name'=> 'benitto']);
- 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();
});
Keep Learning!!
Top comments (0)