each() and contains()

Loop over items with each() and test membership with contains().

Syntax$collection->each(function ($item) { ... });

The each() method iterates over the items and runs a callback — useful for side effects like printing. The contains() method returns true if the collection holds a given value.

Unlike map(), each() does not build a new collection; it returns the original.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A notification service loops over a collection of subscribers with each() to dispatch an individual email job per subscriber.
  • A debugging script uses each() with a closure to dump each item to the log, then returns false from inside one iteration to stop early.
  • A bulk-update job calls each() on a collection of models to call save() on every record without loading them all into a second array.

More examples

Log every item with each()

Iterates over each email address and writes an info log entry — a common pattern for side effects.

Example · php
collect(['[email protected]', '[email protected]'])
    ->each(function (string $email) {
        Log::info('Processing: ' . $email);
    });

Stop iteration early by returning false

Returning false from the each() callback halts iteration immediately, acting like a break statement.

Example · php
$found = null;

collect(range(1, 100))->each(function ($n) use (&$found) {
    if ($n % 17 === 0) {
        $found = $n;
        return false; // stop the loop
    }
});
// $found === 17

Check membership with contains()

contains() checks whether a value exists in the collection, and also accepts a callback for custom match logic.

Example · php
$roles = collect(['editor', 'moderator', 'admin']);

$isAdmin = $roles->contains('admin');     // true
$hasSuperAdmin = $roles->contains('super-admin'); // false

// With a callback
$hasPrivilege = $roles->contains(fn($r) => str_starts_with($r, 'mod'));
// true

Discussion

  • Be the first to comment on this lesson.