0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelでLeague/Csvを使ってDBから取得したデータをcsvで吐き出す

Posted at

前提

この記事の続編ですので環境構築などはこの記事を参照してください。
LaravelでLeague/Csvを使ってアップロードされたcsvを読み込みDBに保存する

やりたいこと

Eloquentで取得したデータをcsvに吐き出し、webからダウンロードできるようにしたい。

実装

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

    // csvのヘッダーを配列で渡す
    $csv->insertOne(['id', '名前', '企業', 'メールアドレス']);

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

    return new Response($csv->getContent(), 200, [
        'Content-Encoding' => 'none',
        'Content-Type' => 'text/csv; charset=UTF-8',
        'Content-Disposition' => 'attachment; filename="'.'ファイル名.csv'.'"',
        'Content-Description' => 'File Transfer',
    ]);
}

実際の使い方

僕が使った時はServiceクラス作って

ClientController.php
public function exportCSV(ClientCsvExportService $service)
{
    return $service->setHeader(['id', '名前', '企業', 'メールアドレス'])
                ->setFileName(now().'ファイル名.csv')
                ->export();
}

的な感じで抽象化しました。
ClientCsvExportService内でLeague/csvを使ってます。

感想

めっちゃ楽だった。
csvインポートでLeague/csv使った時はShift_JIS対応のためのShift_JISとUTF-8での処理の分岐がめんどかったんです。
楽な書き方がエンコードするとできなくなるみたいなのがあって…
けど、今回はとても楽で良かったです。

参考文献

https://mattstauffer.com/blog/export-an-eloquent-collection-to-a-csv-with-league-csv/
https://csv.thephpleague.com/9.0/connections/output/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?