Am trying to download a file I'm creating on the fly (Vue, Laravel, Inertia)
I've got a normal (<a>) link pointing to my download route, however I got this error:
Return value must be of type Illuminate\Http\Response|Illuminate\Http\RedirectResponse|Illuminate\Http\JsonResponse, Symfony\Component\HttpFoundation\StreamedResponse returned
Relevant code:
Controller code
$csv = new CsvGenerator('test');
$csv->addData([
'first' => 'never',
'second' => 'gonna',
'third' => 'give',
]);
return response()->streamDownload($csv->getStreamCallback(), $csv->getFilename(), $csv->getHeaders());
The CSV Generator class
class CsvGenerator
{
private $filename = 'generic';
private $headers = [];
private $data = [];
private $dataHeaders;
public function __construct(string $filename) {
$this->filename = $filename . '-' . now()->timestamp;
$this->dataHeaders = collect([]);
$this->headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename=' . $this->filename . '.csv',
'Expires' => '0',
'Pragma' => 'public',
];
}
public function getFilename() {
return $this->filename;
}
public function setData(array $data) {
$this->data = $data;
foreach ($data as $item) {
$this->dataHeaders = $this->dataHeaders->union(array_keys($item))->unique();
}
}
public function clearData() {
$this->data = [];
}
public function addData(array $entry) {
$this->data[] = $entry;
$this->dataHeaders = $this->dataHeaders->union(array_keys($entry))->unique();
}
public function getData() {
return $this->data;
}
public function setDataHeaders(array $headers) {
$this->dataHeaders = collect($headers);
}
public function getDataHeaders() {
return $this->dataHeaders->toArray();
}
public function getHeaders() {
return $this->headers;
}
public function getStreamCallback() {
$dataHeaders = $this->dataHeaders->toArray();
$data = $this->data;
return function () use ($dataHeaders, $data) {
$handle = fopen("php://output", "w");
fputcsv($handle, $dataHeaders);
foreach ($data as $row) {
fputcsv($handle, $row);
}
fclose($handle);
};
}
public function getResponseObject(): StreamedResponse {
return response()->streamDownload($this->getStreamCallback(), $this->filename, $this->headers);
}
}