0
0

More than 1 year has passed since last update.

EloquentのCollectionをCSVファイルにする

Posted at

DBから取得したEloquentのCollectionをCSVファイルにしたい!

一応コードとしては掛けたのですが、もっといいCollectionの機能がありそうなので助言ありましたらお願いします…。

やり方としては各Eloquentをarrayにしてkeyをarray_valuesで配列にして、implodeで結合してます。
最後にjoinで改行でくっつけています。
注意点としては最後の ->join("\n") ですが、->join('\n') とシングルクォーテーションだと改行コードとして認識されないので必ずダブルクォーテーションにする必要があります。

$collection_string = $collection->map(function ($item, $key) {
    return implode(',' ,array_values($item->toArray()));
})->join("\n");

Storage::disk('example-backet')->put('hoge.csv', $collection_string);
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