← BACK
Laravel / Cache

Avoid map() When Not Transforming: Use each()

Punyapal Shah • • 1 min read
edit this tip →

Use each() for iteration side effects like sending emails; use map() exclusively when returning a transformed collection.

Using map() purely for side effects builds an unused array in memory. Use each() to communicate intent when performing actions without modifying the collection elements.

// BAD: Builds a useless array of nulls in memory
$users->map(function ($user) {
    $user->notify(new MonthlyReport());
});

// GOOD: Expresses iteration intent clearly without allocating memory
$users->each(function ($user) {
    $user->notify(new MonthlyReport());
});
  • map() constructs and returns a new transformed collection instance
  • each() performs side-effect actions and returns the original collection
  • Keeps memory footprint lower and code intent explicit

Related Tips

View all tips →
Laravel Collections

Group Consecutive Items with chunkBy()

Use chunkBy() to split a Collection whenever the resolved value changes, without manually comparing items with the previous chunk.

READ >

// Got a tip in mind? Contributions are always welcome