Laravel - Query Builder - Streaming Results Lazily
The lazy
method works similarly to the chunk
method in the sense that it executes the query in chunks. However, instead of passing each chunk into a callback, the lazy()
method returns a LazyCollection
, which lets you interact with the results as a single stream:
use Illuminate\Support\Facades\DB;
DB::table('users')->orderBy('id')->lazy()->each(function ($user) {
//
});
Once again, if you plan to update the retrieved records while iterating over them, it is best to use the lazyById
method instead. This method will automatically paginate the results based on the record's primary key:
DB::table('users')->where('active', false)
->lazyById()->each(function ($user) {
DB::table('users')
->where('id', $user->id)
->update(['active' => true]);
});
When updating or deleting records while iterating over them, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the results.