0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シーダーを作成するときにcsvを利用する方法

Posted at

データを一括で登録

備忘録です

手順

  1. 以下のようなCSVファイルを用意する

    database/seeders/sample.csv
    title,description,start_date,end_date
    タイトル1,説明1,-20,-10
    タイトル2,説明2,-10,-5
    タイトル3,説明3,5,10
    
  2. シーダーファイルでCSVを読み込むようにする

    database/seeders/SampleSeeder.php
    <?php
    
    namespace Database\Seeders;
    
    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\DB;
    use League\Csv\Reader;
    
    class SampleSeeder extends Seeder
    {
        public function run()
        {
            $csv = Reader::createFromPath(database_path('seeders/sample.csv'), 'r');
            $csv->setHeaderOffset(0);
            $records = $csv->getRecords();
    
            foreach ($records as $record) {
                DB::table('sample')->insert([
                    'title' => $record['title'],
                    'description' => $record['description'],
                    'start_date' => $record['start_date'],
                    'end_date' => $record['end_date'],
                ]);
            }
        }
    }
    
    

    league/csvライブラリを使うには、事前にインストールする

    composer require league/csv
    
  3. シーダーの実行

    database/seeders/DatabaseSeeder.phpを編集して、SampleSeederを呼び出すようにする

    database/seeders/DatabaseSeeder.php
    <?php
    
    namespace Database\Seeders;
    
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
            $this->call(SampleSeeder::class);
        }
    }
    
    

    シーダーを実行して、データベースにデータを挿入する

    php artisan db:seed
    
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?