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 →Use Cache for Short-Lived Tokens Instead of Database Columns
Store temporary verification tokens, OTPs, and one-time codes in Laravel's cache with a defined TTL instead of adding temporary columns to database tables.
Group Consecutive Items with chunkBy()
Use chunkBy() to split a Collection whenever the resolved value changes, without manually comparing items with the previous chunk.