Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away