Skip to content

Conversation

@devfrey
Copy link
Contributor

@devfrey devfrey commented Oct 7, 2021

As described in #39003, looping over a LazyCollection using @foreach in Blade causes the entire collection's iterator to be unwound. This causes duplicate queries and unnecessary model hydration when using lazy collections with Eloquent (because everything would be loaded into memory – twice).

This change skips calling count() on lazy collections, which preserves its 'laziness' until actually looping over the items.

This PR could be considered a breaking change (therefore targeted towards 9.x), because certain information on the loop variable is lost. $loop->remaining, $loop->count, and $loop->last will be null after this change when looping over a lazy collection. If one would want to keep this behaviour, calling ->collect() on the lazy collection would mimic that.

@taylorotwell taylorotwell merged commit b25f211 into laravel:master Oct 8, 2021
@devfrey devfrey deleted the lazy-collection-loop branch October 9, 2021 15:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants