LoginSignup
0
0

More than 3 years have passed since last update.

Lalavelのseeding

Last updated at Posted at 2020-06-04

laravelのFakerクラスのseedeing

seedingの流れ

1)DB接続
2)seedの日本語化
3)modelファイル作成
4)migrateファイル作成
5)DBテーブル作成
6)seedファイル作成
7)factoryファイル作成
8)seeding実行

DBの設定(postgres)

config/database.php
    'default' => env('DB_CONNECTION', 'pgsql'),
.env
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=laravel
DB_USERNAME=postgres
DB_PASSWORD=

seedデータの日本語化

app/config/app.php
    'faker_locale' => 'ja_JP',

modelファイルを作成する

$ php artisan make:model hoge

Model created successfully.

migrateファイルの作成

$ php artisan make:migration create_hoge_table

Created Migration: 2020_06_04_211755_create_hoge_table
app/database/migrations
    public function up()
    {
        Schema::create('hoge', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('last_name');
            $table->string('first_name');
            $table->integer('age')->nullable();
            $table->string('postal')->nullable();
            $table->string('address')->nullable();
            $table->string('tel')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }

DBテーブルの作成

$php artisan migrate

Migrating: 2020_06_04_122729_create_hoge_table
Migrated:  2020_06_04_122729_create_hoge_table (0.01 seconds)

seederファイルの作成

$ php artisan make:seeder HogeTableSeeder

Seeder created successfully.
app/database/seeds
class HogeTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App/HogeTableSeeder::class, 50)->create();
    }
}

factoryファイルを作成する

$ php artisan make:factory HogeFactory

actory created successfully.
app/database/factories

use App\Hoge;

$factory->define(Hoge::class, function (Faker $faker) {
    return [
        'last_name' => $faker->lastName,
        'first_name' => $faker->firstName,
        'age' => $faker->numberBetween(8, 80),
        'postal' => $faker->postcode,
        'address' =>  $faker->address,
        'tel' =>  $faker->phoneNumber,
    ];
});

seedingでダミーデータを、DBに挿入する。

$ php artisan db:seed

Seeding: HogeTableSeeder
Seeded:  HogeTableSeeder (0.15 seconds)
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