Skip to content

[13.x] Avoid creating extra model instances in Eloquent cursor() - #62001

Merged
taylorotwell merged 1 commit into
laravel:13.xfrom
xurshudyan:eloquent-cursor-model-instances
Oct 14, 2026
Merged

taylorotwell merged 1 commit into
laravel:13.xfrom
xurshudyan:eloquent-cursor-model-instances

Conversation

@xurshudyan

Copy link
Copy Markdown
Contributor

cursor() builds three models for every row: the one it returns, plus two throwaway instances from newModelInstance().

This creates that instance once before the loop, like get() already does.

// Exporting orders to a CSV file
foreach (Order::where('status', 'paid')->cursor() as $order) {
    fputcsv($file, [$order->id, $order->total, $order->created_at]);
}

Iterating 10,000 rows goes from 497 ms to 235 ms on my machine. The returned models are the same.

@taylorotwell
taylorotwell merged commit 43a4488 into laravel:13.x Oct 14, 2026
64 checks passed
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