LaravelのSeederについて

  • DatabaseSeederに呼び出し追加
<?php

namespace Database\\Seeders;

use Illuminate\\Database\\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            UserSeeder::class, // 呼び出すように追加
        ]);    }
}
  • UserSeederにcreate行を作成
<?php

namespace Database\\Seeders;

use Illuminate\\Database\\Seeder;
use Illuminate\\Support\\Facades\\DB;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        \\App\\Models\\User::factory(10)->create();
    }
}
  • UserFactoryでフィールド設定
<?php

namespace Database\\Factories;

use Illuminate\\Database\\Eloquent\\Factories\\Factory;
use Illuminate\\Support\\Str;

class UserFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        //ランダムなUserを作成します
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => bcrypt('11111111'),
            'remember_token' => Str::random(10),
            'user_type' => random_int(0, 2),
            'status' => random_int(0, 2),
            'sex' => random_int(0, 2),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return \\Illuminate\\Database\\Eloquent\\Factories\\Factory
     */
    public function unverified()
    {
        return $this->state(function (array $attributes) {
            return [
                'email_verified_at' => null,
            ];
        });
    }
}
  • seeder実行で作成
% php artisan db:seed


参考記事
LaravelのSeeding機能を利用してダミーデータを一括挿入 | アールエフェクト