/* Create the csv to download */
public function downloadCsv(Exporter $exporter, string $query, Collection $records, array $columnMap)
{
$exceptions = [];
$processedRows = 0;
$successfulRows = 0;
$csv = \League\Csv\Writer::createFromFileObject(new SplTempFileObject());
$csv->setDelimiter(',');
$query = EloquentSerializeFacade::unserialize($query);
foreach ($exporter->getCachedColumns() as $column) {
$column->applyRelationshipAggregates($query);
$column->applyEagerLoading($query);
}
$csv->insertOne(array_values($columnMap));
foreach ($records as $record) {
try {
$csv->insertOne(($exporter)($record));
$successfulRows++;
} catch (\Throwable $exception) {
$exceptions[$exception::class] = $exception;
}
$processedRows++;
}
// Return the CSV content as a downloadable response
// Create a StreamedResponse to output the CSV content
$response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($csv) {
echo $csv->toString();
});
// Set the headers to force download
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="data.csv"');
if ($response) {
/* Do we prompt the user to download */
Notification::make()
->title("Exporting CSV file")
->body("Exporting content to CSV file")
->success()
->duration(5000)
->send();
}
return $response;
}