Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

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.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month 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.

Comments

What are your thoughts on "Laravel's tap helper function explained"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.