Laravel's tap helper function explained
A little known helper function, called tap
was added to Laravel 5.3. In this short post I'll explain how this function can be used.
Let's first take a look at the tap
function itself. It's actually a very short one.
function tap($value, $callback)
{
$callback($value);
return $value;
}
So you give it a $value
and a $callback
. The $callback
will execute with the $value
as the argument. And finally the $value
will be returned.
Nice, but how is it used in the wild? Let's take a look at the pull
function in Illuminate\Cache\Repository
. This function will get the value out of the cache for the specified key and forget it.
This is how it could have been implemented:
public function pull($key, $default = null)
{
$value = $this->get($key, $default);
$this->forget($key) // returns a boolean;
return $value;
}
In the example above $this->forget()
returns a boolean. So to have our function return the original value, we need to store it in the temporary variable $value
first.
This is the actual implementation in Laravel.
public function pull($key, $default = null)
{
return tap($this->get($key, $default), function ($value) use ($key) {
$this->forget($key);
});
}
In the snippet above there's no need anymore for a temporary variable. Win! Now, you might argue that it's less readable. If the arrow functions rfc gets accepted, it can be rewritten as a one liner.
public function pull($key, $default = null)
{
return tap($this->get($key, $default), fn($value) => $this->forget($key));
}
Want to see some more usages of tap
? Take a look at the Laravel source code. There's also a tap
method on the Collection
class. Read this post on Laravel news to see a few examples.
What are your thoughts on "Laravel's tap helper function explained"?