Peeking into Laravel Collections with the `tap()` method

Laravel devs, here's a gem for you: πŸ’Ž

The Laravel Collection class offers numerous methods to manipulate and interact with data efficiently. One particularly useful method is tap(), which allows you to "peek" into a collection and perform side effects without modifying the collection itself. This method is perfect for logging, debugging, or performing other operations on a collection without altering its state. Let's explore how to use the tap() method with an example.

What is tap()?

The tap() method allows you to pass the collection to a callback function where you can perform any desired operations. The original collection is returned unmodified, allowing you to continue chaining other collection methods. This is particularly useful for logging, debugging, or side effects where you need to inspect or interact with the collection without changing it.

Example: Logging Collection Information

Suppose you have a collection of numbers and you want to log the collection size before doubling the numbers. Using tap(), you can log the information without affecting the collection's transformation.

Step-by-Step Implementation

  1. Creating the Collection

Start by creating a collection of numbers:

$collection = collect([2, 4, 6, 8]);
  1. Using the tap() Method

Use the tap() method to log the size of the collection before applying transformations:

$doubledNumbers = $collection->tap(function ($collection) {
    Log::info('Collection size: ' . $collection->count());
})->map(function ($number) {
    return $number * 2;

// Result: [4, 8, 12, 16]
// Log entry: Collection size: 4

In this example, the tap() method logs the size of the collection without modifying it. The map() method then doubles the numbers in the collection.

Additional Examples

  • Performing Side Effects

Use tap() to perform side effects, such as sending notifications or updating logs, without affecting the collection:

$users = collect([
    ['name' => 'John', 'email' => ''],
    ['name' => 'Jane', 'email' => ''],

$updatedUsers = $users->tap(function ($collection) {
    $collection->each(function ($user) {
        Mail::to($user['email'])->send(new WelcomeEmail($user));
})->map(function ($user) {
    $user['status'] = 'emailed';
    return $user;

// Result: [['name' => 'John', 'email' => '', 'status' => 'emailed'], ['name' => 'Jane', 'email' => '', 'status' => 'emailed']]


The tap() method is a versatile and powerful addition to the Laravel Collection methods, enabling you to perform side effects, log information, and debug data transformations without modifying the original collection. By using tap(), you can maintain clean, non-intrusive, and efficient code, making it easier to manage and debug your Laravel applications.

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.