0
1

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でCSVする方法

Posted at

はじめに

FuelPHPには Format:forge($array)->toCsv() という感じで配列からかんたんにCSV用の文字列を生み出すことができたのですが、Laravelにはありません。
http://fuelphp.jp/docs/1.9/classes/format.html

それくらい foreach でぐるぐる回せやってのはあるのでしょうけど、めんどくさいじゃないですか。
そこでいい方法がないかなって探してみました。

soapbox/laravel-formatter を入れる

まあ、だいたいこういうものはpackagist漁ればいいのがありそうなもんなんですよ。
Laravel用じゃなくてもいいのですが、Laravel用だと5.5以降ならServiceProviderにいちいち登録しなくても使えるのがいいですよね!

というわけで今回は soapbox/laravel-formatter というのを使ってみます。
https://packagist.org/packages/soapbox/laravel-formatter

こいつを composer require しましょう。

$ composer require soapbox/laravel-formatter

これでLaravel内で Formatter として使えるようになっているので、あとは以下の感じで行けるはずです。
基本的には連想配列のキーがそのままラベル行として使われるので、DBから引っ張ってくるときにカラム名をas使って日本語とかにすると使いやすいと思います。

use SoapBox\Formatter\Formatter;

class HogeService
{
    public function makeCsvData()
    {
        $list = $this->hogeRepository->listForDownload();
        $formatter = Formatter::make($list->toArray(), Formatter::ARR);

        return $formatter->toCsv();
    }
}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?