LoginSignup
19
25

More than 5 years have passed since last update.

Laravelでcsvファイルからデータを一括で取り込む

Last updated at Posted at 2015-08-04

概要

Laravelプロダクトで大量の初期データを流し込む必要があったので、その備忘録です。
csvファイルをパースするために、goodby/csv を使用しています。

composerからライブラリを取り込む

composer.jsonに追記

composer.json
"require-dev": {
    ~~~,
    "goodby/csv": "1.2.0",
}
いつものやつ
$ composer update

流し込むためのクラス生成

今回はLaravelのSeederクラスを使ってインポートしました。

app/database/seeds/InitialExampleDataSeeder.php
<?php

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

class InitialExampleDataSeeder extends Seeder
{
    const CSV_FILENAME = 'path/to/file';

    public function run()
    {
        $this->command->info('[Start] import data.');

        $config = new LexerConfig();
        // セパレーター指定、"\t"を指定すればtsvファイルとかも取り込めます
        $config->setDelimiter(",");
        $lexer = new Lexer($config);
        $interpreter = new Interpreter();
        $interpreter->addObserver(function(array $row) {
            // 各列のデータを取得
            $first = $row[0];
            $second = $row[1];

            // 登録処理をここに書く
        });

        $lexer->parse(app_path() . self::CSV_FILENAME, $interpreter);

        $this->command->info('[End] import data.');
    }
}

Seeder実行

$ php artisan db:seed --class=InitialExampleDataSeeder
19
25
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
19
25