Skip to content

[8.x] Document lazy loading eloquent results #7576

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

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions eloquent.md
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,20 @@ When interacting with Eloquent models, you may also use the `count`, `sum`, `max
$max = Flight::where('active', 1)->max('price');

<a name="inserting-and-updating-models"></a>

<a name="lazy-eloquent"></a>

### Lazy Loading Results

When dealing with large tables, you may wish to reduce memory usage. Historically this would be done using [lazy ollections](/docs/{{version}}/collections#lazy-collections). As of Laravel version 8.78.0, you can use the `lazy` method at the end of your Eloquent queries to split your database results and work on very large datasets, whilst keeping your memory usage low. Laravel will load your data into chunks on demand, which clears memory after each chunk is used. You may specify the chunk size as an integer greater than 1. Passing a chunk size less than 1 will result in `InvalidArgumentException` being thrown.

The result of this lazy loading is a flattened `LazyCollection` instance, that you can use like regular collections, without the worry of running out of memory:

$flights Flight::where('departed', true)->lazy(100)

$flights->each->archive();

> {tip} You can also use `lazyByIdDesc` to lazy load a large data based on the descending order of the ID, complementing the existing `lazyById`.
## Inserting & Updating Models

<a name="inserts"></a>
Expand Down