LoginSignup
20
26

More than 5 years have passed since last update.

【Laravel】CSVファイルのデータをSeederでDBにつっこむ

Posted at

file_get_contents() だとメモリ不足になってエラーになったりする、らしいので SplFileObject クラスを使う。

m_category.csv
A,ビジネス
B,教育
C,医療
D,福祉
...
CategoryTableSeeder.php
    public function run()
    {
        $file = new SplFileObject('database/csv/m_category.csv');
        $file->setFlags(
            \SplFileObject::READ_CSV |
            \SplFileObject::READ_AHEAD |
            \SplFileObject::SKIP_EMPTY |
            \SplFileObject::DROP_NEW_LINE
        );
        $list = [];
        $now = Carbon::now();
        foreach($file as $line) {
            $list[] = [
                "label" => $line[0],
                "name" => $line[1],
                "created_at" => $now,
                "updated_at" => $now,
            ];
        }

        DB::table("m_category")->insert($list);
    }

参考

https://www.ritolab.com/entry/63
https://qiita.com/suin/items/31a1c7c47f49cb53f2a7
https://qiita.com/kazu56/items/bc77582313918fe2a3b1
http://php.net/manual/ja/splfileobject.fgetcsv.php
https://qiita.com/tadsan/items/bbc23ee596d55159f044#splfileobject

20
26
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
20
26