Search code examples
laravelcsvexport-to-csv

How to export csv file in laravel 9


How can I export a csv file in laravel 9.

    $fileName = 'file.csv';
    $callback = function() use($records, $fileName) {
        $date = (date("Y-m-d h:i:s"));
        $fp = fopen($fileName, 'w');
        fwrite($fp,"Export Data\nDate:".$date."\n\n\n");                
        foreach ($records as $fields) {
            fputcsv($fp, $fields);
        }
            fclose($fp);
    };
    $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"
    );        
    return response()->download($fileName, 'file.csv', $headers);

I have used code provided above to create a csv file, which is working fine and a correct file is being created, but the response I am getting in js front in browser is just the content of files.

console.log(result) gives response below

Export Data

Date:2022-04-20 04:20:69

first_name,last_name,primary_email .....

How can I make the file download in browser?


Solution

  • I just had to put in some JS code to make it download Here is the code I used.

        // Ajax request above this
        let result = response;
        const url = window.URL.createObjectURL(new Blob([result]));
        const link = document.createElement('a');
        var today = new Date();
        var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate() +"_"+ today.getHours() + today.getMinutes() + today.getSeconds();
        link.setAttribute('download', 'Export_Data_'+date+'.csv');
        link.href = url;
        document.body.appendChild(link);
        link.click();