Streaming Downloads: Export Large Files Without Crashing Memory
Stream large CSV/exports efficiently so your Laravel app stays stable.
Megan Stone
October 11, 2025
2.7k79
A common mistake is generating a large export fully in memory and then returning it. This can crash servers.
Streaming sends data chunk by chunk.
## Stream a CSV response
```php
return response()->streamDownload(function () {
$handle = fopen('php://output', 'w');
fputcsv($handle, ['id', 'name', 'email']);
User::query()->chunk(1000, function ($users) use ($handle) {
foreach ($users as $user) {
fputcsv($handle, [$user->id, $user->name, $user->email]);
}
});
fclose($handle);
}, 'users.csv');
```
## Flow
```mermaid
flowchart LR
A[Request Export] --> B[Chunk Query]
B --> C[Write Rows]
C --> D[Stream to Client]
```
In the next tutorial, we will implement advanced search filters with query builders.
#Laravel#Performance#Files#Advanced