Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

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.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • good article. btw, in the last snippet code array function’s parameter does not match the one in the function body.

  • Pingback: Laravel tap 用法-IT文库()

  • That’s nice for removing a temporary variable, but I would argue even the arrow function example is less readable.

  • Eimihar El-Meruiy

    I am sorry but I would hate anyone who does such one liner in my team… anything that reduces readability should be discouraged..