Save to Path an Eloquent Collection to a CSV with League CSV

1.6k Views Asked by At

I have this function that export the csv, the it outputs the file so the user can download it.

 public function export()
{
    $people = Person::all();

    $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());

    $csv->insertOne(\Schema::getColumnListing('people'));

    foreach ($people as $person) {
        $csv->insertOne($person->toArray());
    }

    $csv->output('people.csv');
}

Instead of this I want to save the file in a project folder.

how could i do it?

thanks

1

There are 1 best solutions below

0
On

Don´t use createFromFileObject, instead

$csv = \League\Csv\Writer::createFromPath('path/to/people.csv', 'w');

if the file doesn´t exist, this will create.

And remove $csv->output('people.csv'), it´s not necessary.