I'm currently organising Full Stack Europe. It's a conference in Antwerp, Belgium for developers who want to learn across the stack. You can use this link get your ticket with a nice discount.

Laravel's tap helper function explained

Original – by Freek Van der Herten – 2 minute read

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.

Stay up to date with all things Laravel, PHP, and JavaScript.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.