tap()
is one of Taylor Otwell's favorite helper methods
.
If you look through Laravel's codebase, you'll see tapping in all kinds of places.
But what does tap actually do?
tap()
is a global helper function in Laravel.
You can call tap from anywhere in your codebase.
This is tap's function definition:
function tap($value, $callback = null)
{
$callback($value);
return $value;
}
The tap helper accepts a value and a callback. It then passes the value into the callback, and returns the value. Let's look at an example from inside Eloquent:
public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}
Tap is used to return the new model instance.
The result of save()
can't be returned directly because it returns a success boolean.
The advantage of tap is that the code doesn't require a temporary variable.
Below is the same code, but without tap:
public function create(array $attributes = [])
{
$instance = $this->newModelInstance($attributes);
$instance->save();
return $instance;
}
Tap is a matter of preference, some love it, some hate it. The end result is the same.
So far, we've talked about the global tap helper.
But you can also make your classes tappable by using the Tappable trait
.
Many classes in the Laravel framework are tappable by default.
When a class is tappable, you can call tap()
while chaining methods.
Take this example from the Collection
class:
User::get()
->tap(function (Collection $collection) {
info('Processing '.$collection->count().' users...');
})
->each(function (User $user) {
// ...
});
In the example above, the tap method receives the collection, but does not break the fluent chain. Consider the same code without tap:
$users = User::get();
info('Processing '.$collection->count().' users...');
$users->each(function (User $user) {
// ...
});
In this example, using tap is the clear winning in my opinion.
Level up your Laravel deployments
If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.
Deploy with GitHub Actions
Deploy with GitLab CI/CD