nafeeur10's avatar

What is the real use of tap helper function in Laravel

$response = tap($kernel->handle(
    $request = Request::capture()
))->send();

https://medium.com/@taylorotwell/tap-tap-tap-1fc6fc1f93a6 I read this article but can't understand the real use of Tap method.

Some good open source project also use it. For example: https://github.com/koel/koel/blob/master/app/Services/InteractionService.php

But I can't understand!!! How it works and When I should use it?

Can anyone give me a simple example?

0 likes
2 replies
martinbean's avatar
Level 80

@nafeeur10 Tapping is used to do something with a variable before returning it.

So, imagine you’re fetching a model, want to call a method on that model, and then return the model. Traditionally, you might do something like this:

public function findArticleAndIncreaseView($id)
{
    $article = Article::findOrFail($id);

    $article->incrementViews();

    return $article;
}

Instead of calling the method and then returning, we can use tap instead:

public function findArticleAndIncreaseView($id)
{
    return tap(Article::findOrFail($id), function (Article $article) {
        $article->incrementViews();
    });
}

So, the first argument is the value. The second argument is a closure that will receive that value, inside which you can do what you want, before tap then returns the value.

23 likes

Please or to participate in this conversation.