phplaravelexport-to-csv

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


Solution

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