Understanding and Utilizing tap() in Laravel

Binu Mathew
3 min readJun 25, 2024
Photo by Florian Olivo on Unsplash

The tap() function is a handy utility in Laravel that allows you to work with a value and perform operations on it without affecting the original value. It's part of Laravel's collection of "higher-order" functions that aim to make your code more expressive and concise.

Why Use tap()?

  1. Improved readability: tap() can make your code more readable by reducing the need for temporary variables.
  2. Method chaining: It allows you to perform operations in the middle of a method chain without breaking the chain.
  3. Side effects: You can execute side effects on an object without altering the main flow of your code.

When to Use tap()

  1. Use tap() when you want to:
  2. Perform an action on a value without changing the value itself.
  3. Execute a side effect in the middle of a method chain.
  4. Improve the readability of your code by eliminating temporary variables.

How tap() Works

  1. The tap() function accepts two arguments:
  2. The value you want to work with.
  3. A closure that receives this value as an argument. It then returns the original value, regardless of what the closure does.

Examples

Let’s dive into some practical examples to see how tap() can be used in Laravel applications.

Example 1: Performing Actions Without Breaking the Chain

$user = tap(User::find(1), function($user) {
$user->update(['last_login' => now()]);
Log::info("User {$user->name} logged in");
});

// Now $user is still the User model, not affected by the update or log operations

In this example, we’re finding a user, updating their last login time, and logging the action. Without tap(), we might need to break this into multiple lines or use a temporary variable. With tap(), we can do all of this in one fluent statement.

Example 2: Conditional Updates in Eloquent

$post = Post::create($validatedData);

return tap($post, function ($post) use ($request) {
if ($request->hasFile('image')) {
$post->addMedia($request->file('image'))->toMediaCollection('featured');
}

if ($request->has('tags')) {
$post->tags()->attach($request->tags);
}
});

Here, we’re creating a new blog post and then conditionally adding an image and tags. The tap() function allows us to perform these conditional operations without breaking the flow of returning the newly created post.

Example 3: Debugging in Method Chains

$result = collect([1, 2, 3, 4, 5])
->map(function ($n) { return $n * 2; })
->tap(function ($collection) {
Log::debug('After doubling:', $collection->all());
})
->filter(function ($n) { return $n > 5; })
->tap(function ($collection) {
Log::debug('After filtering:', $collection->all());
})
->sum();

In this example, we’re using tap() to log the state of our collection at different points in a method chain. This can be incredibly useful for debugging complex operations without interrupting the flow of the code.

Photo by Joshua Earle on Unsplash

Conclusion

The tap() function in Laravel is a powerful tool for writing more expressive and maintainable code. By allowing you to perform operations or side effects without affecting the main flow of your code, it can significantly improve readability and reduce the need for temporary variables.

Whether you're working with Eloquent models, collections, or any other value, tap() can be a valuable addition to your Laravel toolkit. Remember, the key to using tap() effectively is to identify situations where you need to perform an action without altering the value being passed through your code.

With practice, you'll find numerous opportunities to leverage this useful function in your Laravel applications.

--

--