1
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?

More than 5 years have passed since last update.

Laravel seedingでDBへ初期データを自動投入する

Last updated at Posted at 2019-12-10

マイグレーションファイルを作成し、マイグレーション実行しDBにテーブルがあることを確認した後、
次にseederを使って初期データを追加する作業に移ります。

このseederというものを使えば簡単にDBへ初期データを入れることができます。

アジェンダ
1.Seedファイルの生成
2.シーダークラスの定義
3.シーダクラスをコールする為の設定
4.オートローダ再生成
5.シーディング実行
6.マイグレーションとシーディングでデータベースを再構築する

Seedファイルの生成

まず初めに投入するデータを記述するseedファイルを生成します。
その前に公式にならって、シーダクラス名を決めます。
"App"TableSeederのようにTableSeederが後に続いたシーダクラス名にします。

シーダー生成のartisanコマンド

php artisan make:seeder AppTableSeeder

そうすると
laravel/database/seeds 配下に AppTableSeeder.phpが生成されます。

シーダークラスの定義

laravel/database/seeds/AppTableSeeder.php

run()メソッドにデータを投入する記述を行う。


use Illuminate\Database\Seeder;

class AppTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
       $param = [
            'name' => Str::random(10),
            'email' => Str::random(10).'@yamada.jp',
            'password' => bcrypt('password'),
            'birthday' => '2000/01/01',
        ];
        DB::table('users')->updateOrInsert($param);

        $param = [
            'name' => Str::random(10),
            'email' =>  Str::random(10).'@yamada.jp',
            'password' => bcrypt('password'),
            'birthday' => '2000/01/01',
        ];
        DB::table('users')->updateOrInsert($param);
       
        $param = [
            'name' => Str::random(10),
            'email' =>  Str::random(10).'@yamada.jp',
            'password' => bcrypt('password'),
            'birthday' => '2000/01/01',
        ];
        DB::table('users')->updateOrInsert($param);
    
    }
}

シーダークラスをコールするための設定

シーダクラスの定義が完了したら、このシーダークラスをシーディング実行時にコールできるようにします。

laravel/database/seeds/DatabaseSeeder.php


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
          AppTableSeeder::class,
        ]);
    }
}

オートローダ再生成

composerのオートローダーを再生成します。

composer dump-autoload

シーディング実行

それでは早速シーディングの実行をしていきます。
Laravelのルートディレクトリに移動し、コマンドを叩きます。

php artisan db:seed

実行が完了したら、実際にmysqlでデータを確認してみます。

ここまででシーダクラスに手動で情報をインサートし、シーディングを行うことができました。

参考文献

PHPフレームワーク Laravel入門

1
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
1
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?