Nurul Alam
Nurul Alam

Reputation: 352

Exporting CSV response laravel 5.5 and download as csv file

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

Upvotes: 4

Views: 9332

Answers (2)

Sapnesh Naik
Sapnesh Naik

Reputation: 11646

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);

Upvotes: 3

Christophvh
Christophvh

Reputation: 13224

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

Upvotes: 1

Related Questions