Justoverclock use the Laravel query builder each()
function, or chunk()
(chunk
is used internally for each
)
User::each(function ($user) {
echo "{$user->username}\n";
});
It can be put at the end of any query:
// Build query, but do not call get()
$query = User::where('is_email_verified', true);
// If you need to track progress, you can query how many results there will be in advance
$total = $query->count();
$query->each(function ($user) {
echo "{$user->username}\n";
});
By default I believe it will retrieve 100 results from the database, then loop through each of them and call the callback, then repeat with the next chunk. The second parameter can be used to customize how many models are retrieved per SQL request ("chunk").
Also consider putting such code in a console command or a queable job, so that it can be run without any memory or time limit.