Laravel 5.5 — Higher Order Tap

Khalid Dabjan
Aug 24, 2017 · 1 min read

Higher order tap is a feature that comes with Laravel 5.5, it is an improvement over the somehow “controversial” tap() function.

First, a little background on tap when it was released with laravel 5.4 (I think?). The idea behind it is to “tap” into a value, manipulate it via a closure that you pass and then return this value. so something like:

$user->update([
'name' => 'Phoebe Buffay'
]);
return $user;

could be turned into:

return tap($user, function ($value) {
$value->update([
'name' => 'Phoebe Buffay'
]);
});

But now with 5.5 the closure parameter is optional, so…:

return tap($user)->update([
'name'=>'Phoebe Buffay'
]);

Which is Awesome, and -I’m gonna say it- Magical! Well, unfortunately no real magic is taking place here. taking a look at the implementation of tap:

function tap($value, $callback = null)
{
if (is_null($callback)) {
return new HigherOrderTapProxy($value);
}

$callback($value);

return $value;
}

It checks if the $callback is null and it delegates to a class called HigherOrderTapProxy in case it was. This class implements the __call() magic method:

public function __call($method, $parameters)
{
$this->target->{$method}(...$parameters);

return $this->target;
}

What do you, there was some magic involved after all :)

)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade