4

I am trying to export and download some data in a csv file using an ajax request. I was able to output the data in a json response to test but could not get it to download in a data.csv file

Following is the code I have written so far

 public function download(Request $request) { if(!empty($request->input('my_checkbox'))) { $studentIdToExportArray = $request->input('my_checkbox'); //$msg = is_array($studentIdToExportArray);//returns true $selectedStudents = []; foreach($studentIdToExportArray as $student_id) { $student = Students::find($student_id); array_push($selectedStudents, $student); } header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=data.csv'); $output=fopen("php://output","w"); fputcsv($output,array("ID","firstname","surname","email","nationality","address_id","course_id")); foreach($selectedStudents as $s1) { $array = json_decode(json_encode($s1), true); fputcsv($output, $array); } fclose($output); return response()->json([ 'test'=> $selectedStudents ]); } } 

Screenshot of output response in console

enter image description here

Problem: The file data.csv does not download

2 Answers 2

3

Try:

$file=fopen('../storage/app/test.csv','w'); $headers = array( 'Content-Type' => 'text/csv', ); $path = storage_path('test.csv'); return response()->download($path, 'test.csv', $headers); 
Sign up to request clarification or add additional context in comments.

7 Comments

tried it, but it does not download..Laravel.log "Resource id #249" does not exist "
@NurulAlam try with my updated answer, please. you need to change the fopen line and also the file path
the file saves in the storage folder. But it does not download.Could you kindly tell me how do i start the download on a browser?
@NurulAlam Can you tell me where exactly the file is being stored?
@NurulAlam Assuming its the storage folder, I've modified my answer.
|
1

You first have to save the file to a location on your local or a cloud disk and then do a file response or a download response. These are the download options like shown in the docs: https://laravel.com/docs/5.5/responses#file-responses

return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers); return response()->download($pathToFile)->deleteFileAfterSend(true) 

ps: you can also look at using a dedicated package for this, or just use the package as a reference. https://github.com/Maatwebsite/Laravel-Excel

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.