共通関数にでもしておき引数渡してダウンロード
$csv = [
['id','user'],
[1,'a'],
[2,'b']
];
$file_name = 'CSV' . date('YmdHis');
$response = Csv::csv_download($csv, $file_name);
return $response;
<?php
namespace App\Library;
use Illuminate\Support\Facades\Facade;
use Symfony\Component\HttpFoundation\StreamedResponse;
class Csv extends Facade
{
public static function csv_download($data, $fileName)
{
$response = new StreamedResponse(function () use ($data) {
$stream = fopen('php://output', 'w');
// 文字化け回避
stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT');
// データからcsv生成
foreach ($data as $key => $value) {
fputcsv($stream, $value);
}
fclose($stream);
});
$response->headers->set('Content-Type', 'application/octet-stream');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '.csv"');
return $response;
}
}