Sunday, 7 August 2022

Laravel generate csv for database tables column names only

/*-----------Get Sample CSV ----------------- */
public function getSampleCsv(Request $request,$id)
{
$columns= DB::getSchemaBuilder()->getColumnListing($id);
if (($key = array_search('created_at', $columns)) != false) {
unset($columns[$key]);
}
if (($key = array_search('updated_at', $columns)) != false) {
unset($columns[$key]);
}
$fileName = 'sample.csv';
$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"
);
$callback = function() use($columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
};

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 = ...