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.