Export an Eloquent Collection to a CSV with League CSV

Posted on March 02, 2015 | By Matt Stauffer

Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

League/CSV is a wonderfully simple wrapper around PHP's native CSV support, and it's simple to dump your Laravel Eloquent collection results out to CSV.

There's a ton more you can do with CSV, so go check out the docs, but here's a simple recipe to get started:

1. Install CSV

$ composer require league/csv

2. Prep the data

Let's say you're in an export method in your controller.

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

3. Create the CSV file in memory

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

4. Create your headers

You can manually pass an array of your headers, but this is the quick (and very dirty way) you can get it up and running in a prototype:

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

You just inserted a row (insertOne()) filled with an array of the column names from your people table.

5. Insert your rows

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

6. Output it to the user

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

Conclusion

That's it! You're now dumping an entire Eloquent collection result straight to CSV. Let's check it out:

    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');
    }

If someone visits that route, they'll get people.csv downloaded straight into their browser. Done.

Again, check the docs to learn more about it. I hope this helps!

Postscript

I intentionally used foreach in the example to show that you could also do this with any other source of data. But if you are really only using it for Laravel Collections, you could also use Collection->each():

    public function export()
    {
        $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());

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

        Person::all()->each(function($person) use($csv) {
            $csv->insertOne($person->toArray());
        });

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

Comments? I'm @stauffermatt on Twitter


Tags: laravel  •  csv