Laravel Collections Bug Caused by Arrow Functions

May 30, 2026

Freek recently shared a post on X about a bug related to Laravel Collections. The issue was surprising to me because the fix looks almost identical to the original code.

 

The code that triggered the issue:

 

collect([])
    ->each(fn (string $hash) => $this->taggedCache($this->tags)->forget($hash));

 

After the fix:

 

collect([])
    ->each(function (string $hash) {
        $this->taggedCache($this->tags)->forget($hash);
    });

 

At first glance, nothing seems to have changed except for replacing the arrow function with an anonymous function. However, that small difference was enough to cause the bug.

 

Lito highlighted the reason in a comment on the post. The `each()` method stops iterating when the callback returns `false`.

 

With the arrow function:

 

fn (string $hash) => $this->taggedCache($this->tags)->forget($hash)

 

The result of `forget()` is implicitly returned. If `forget()` returns `false`, `each()` interprets that as a signal to stop iterating.

 

With the anonymous function:

 

function (string $hash) {
    $this->taggedCache($this->tags)->forget($hash);
}

 

nothing is returned explicitly, so the callback returns `null` instead of `false`. As a result, `each()` continues iterating without stopping early.

 

It's a subtle difference, but an important reminder that arrow functions always return the value of their expression, which can sometimes lead to unexpected control-flow behavior in callbacks.

AI Assistant

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.