Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Prevent calling count() on LazyCollection in Blade loops #39141

Merged
merged 2 commits into from
Oct 8, 2021
Merged

[9.x] Prevent calling count() on LazyCollection in Blade loops #39141

merged 2 commits into from
Oct 8, 2021

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