Sunday, 7 August 2022

generate csv for unknown database table columns in laravel

 /*-----------export DATA to csv ----------------- */

public function exportDataCsv(Request $request,$id)
{
$fileName = 'data.csv';
$data=DB::table($id)->get();
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns= DB::getSchemaBuilder()->getColumnListing($id);
$callback = function() use($data, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
if(count($data)>0 )
{
foreach($data as $key=> $ob1) {
for($i=0;$i<count($columns);$i++)
{
$col=$columns[$i];
$row[$key][] = $ob1->$col;
}
fputcsv($file,$row[$key]);
}
}else{

fputcsv($file,array('No data'));
}
};
return response()->stream($callback, 200, $headers);
}

No comments:

Post a Comment

Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...