Skip to content

LazyCollection does not work with json streaming responses #57427

@Sparclex

Description

@Sparclex

Laravel Version

12.34.0

PHP Version

8.4.13

Description

When streaming a LazyCollection as JSON, the response is not actually streamed — instead, the entire dataset is loaded into memory.

I found that this happens because LazyCollection implements JsonSerializable via Enumerable, causing it to be serialized in-memory rather than using StreamedJsonResponse.

Proposed Solution

LazyCollection should override the jsonSerialize method from Enumerable to use a more memory-efficient approach, same as StreamedJsonResponse::streamData.

Steps To Reproduce

https://github.com/Sparclex/lazy-collection-json-memory-issue

Run the migrations an go to the start page. You'll find two links one with a lazy collection implementation and one with a generator function wrapped around the lazy collection (for which streaming works).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions