How to Export and Download CSV file without Plugin in Laravel 8/9/10

In this article, we will see how to export and download CSV file in Laravel framework. Exporting CSV file is a common requirement in many applications. Most of the examples around there were based on Laravel extensions so using this article you will be able to download csv using PHP stream with help of fopen and fputcsv functions with custom PHP code.

In this tutorial we will not save our file in public folder or anywhere and will just create it on the fly and send it back to the requester or browser as a stream. In this example of download csv file in Laravel 9 application I will use Reactjs for frontend. You can use simple javascript or any other javascript framework to make Ajax call to the API.

Let’s jump directly onto the frontend code first. As I said I am using Reactjs to download CSV data generated by Laravel backend so this is the javascript code to do the request and download the csv data.

try {
    const response = await axios.get(
        `/api_url_to_generate_and_respond_back_with_csv_data`, 
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/csv'
            }
        }
    ).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `transfer-template-${programId}.csv`); //or any other extension
        document.body.appendChild(link);
        link.click();
    })
    .catch((error) => console.log(error));
} catch (e) {
    throw new Error(`API error:${e?.message}`);
}

Now let’s go into the Laravel controller function which creates the CSV data and responds back with data stream. I have skipped routes and in fact many parts like setup Laravel so this tutorial may not be good for Laravel beginners andI am sorry for that. Here is the controller code anyhow:

public function downloadCsv() {
    $csv = some_function_or_process_to_generate_csv_data_in_array_format(); //here you get csv data in form of array
    $csvFilename = 'your-download_fileName.csv';

    $headers = array(
        "Content-type"        => "text/csv",
        "Content-Disposition" => "attachment; filename=$csvFilename",
        "Pragma"              => "no-cache",
        "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
        "Expires"             => "0"
    );

    $callback = function() use($csv) {
        $file = fopen('php://output', 'w');
        // fputcsv($file, $columns);
        foreach ($csv as $row) {
            fputcsv($file, $row);
        }
        fclose($file);
    };
    return response()->stream($callback, 200, $headers);
}

And here is the some_function_or_process_to_generate_csv_data_in_array_format() function somewhere in a repository, service or may be in a model :

public function some_function_or_process_to_generate_csv_data_in_array_format( Model $model )   {

    $csv = array ();

    $csvHeaderRow = ["Heading 1", "Heading 2", , "Heading 3"];
    $csv[] = $csvHeaderRow; //csv header row

    if( Model::all()->isNotEmpty() ) {
        foreach ( Model::all() as $model ) {
            $csvRow = [ $model->id, $model->name, $model->age];
            $csv [] = $csvRow;
        }
    }
    return $csv;
}

If you did things in right way and after understanding the code well, it should be an easy job for you to download CSV in Laravel . I will try to add more details to this post when I got ample time to do so. Leave me a comment if you needed any help with your code or with your project.

Leave a Reply