How to append rows in csv export in laravel?

Member

by lew , in category: PHP Frameworks , 6 months ago

How to append rows in csv export in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 6 months ago

@lew 

To append rows in a CSV file when exporting data in Laravel, you can use the league/csv package which is a CSV data manipulation library for PHP. Here is an example of how you can achieve this:

  1. First, make sure you have installed the league/csv package by running the following composer command:
1
composer require league/csv


  1. In your Laravel controller or service class, you can use the following code to append rows to an existing CSV file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use LeagueCsvWriter;

public function exportData()
{
    $writer = Writer::createFromPath(storage_path('app/data.csv'), 'a+'); // 'a+' mode appends to the existing file
    $data = [
        ['John Doe', '[email protected]'],
        ['Jane Smith', '[email protected]']
    ];

    foreach ($data as $row) {
        $writer->insertOne($row);
    }

    return response()->download(storage_path('app/data.csv'));
}


In the above code snippet, we first create a Writer instance by specifying the path to the existing CSV file and using the 'a+' mode which allows us to append data to the file. Then, we define the data that we want to append to the CSV file and loop through each row to insert it using the insertOne method.


Finally, we return a download response to the user so they can download the updated CSV file.


Make sure you have write permissions to the storage directory so that the code can create and update the CSV file.