Norway


League/CSV is a wonderfully simple wrapper around PHP’s native support, and it’s simple to dump your Laravel 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 /csv

2. Prep the

Let’s say you’re in an method in your controller.

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

3. Create the CSV file in memory

$csv = LeagueCsvWriter::createFromFileObject(new SplTempFileObject());

. 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 = LeagueCsvWriter::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 = LeagueCsvWriter::createFromFileObject(new SplTempFileObject());

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

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

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



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here