One of my favorite helpers methods in Laravel is
tap. On first glance, this Ruby inspired function is pretty odd. Here is the basic implementation of the function:
As you can see, the function takes any argument and a callback / anonymous function.
tap allows you to do something with the
$value inside of the Closure and then return the
$value. To see how it’s used, let’s look at how the Laravel framework itself uses
tap. Check out the following method from Eloquent:
In this example, we’re creating a new Eloquent model, saving the model, and then returning that model instance back to the caller. The
tap helper allows us to do this in one “block” of code since it always returns the model instance we provide.
In a recent version of Laravel 5.4, we introduced the ability to shorten some
tap calls. This new implementation of tap can be seen here. Let’s take a look at an example:
In this example, we pass a single argument (a User model) to
tap, and then we are able to chain any of that model’s methods onto the
tap call. The
update method normally returns a boolean; however, since we used the
tap function, the
update method will return the User model we tapped. This feature of
tap makes it easy to force any method on an object to return the object itself.
tap is a very simple helper, I find it often lets me write terse, one-line operations that would normally require temporary variables or additional lines. Let me know if you find any other interesting uses of