recovery men recovery men - 20 days ago 11
PHP Question

Export a single record only Headers downing not the data (laravel 5.3)

I am trying to export single record from DB. I have tried to write different methods but failed. Now I try this one here, it's just downloading the headers and no data.

public function getExport($id) {
$student = Students::find($id);
$filename = "students.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('name', 'class', 'section'));

foreach($student as $row) {
fputcsv($handle, array($row['name'], $row['class'], $row['section']));
}

fclose($handle);

$headers = array(
'Content-Type' => 'text/csv',
);

return Response::download($filename, 'Students.csv', $headers);
}


Here it just gives the table head not data below. How can I get all?

Answer

UPDATE v3 according the comments.

public function getExport($id)
    {
        $student = Students::find($id);
        $filename = $student->name . ".csv";
        $handle = fopen($filename, 'w+');
        fputcsv($handle, array('name', 'class', 'section'));
        fputcsv($handle, array($student->name, $student->class, $student->section));

        fclose($handle);

        $headers = array(
            'Content-Type' => 'text/csv',
        );

        return \Response::download($filename, $filename, $headers);
    }
Comments