Laravel Seeder & Factoryの使い方

DatabaseSeederの初期
./database/seeds/DatabaseSeeder.php

public function run()
    {
        $this->call(UsersTableSeeder::class);
    }

### make:seeder
$ php artisan make:seeder UsersTableSeeder
./database/seeds/UsersTableSeeder.php

public function run()
    {
        //
        DB::table('users')->insert([
        	'name'=>str_random(10),
        	'role_id'=>1,
        	'is_active'=>1,
        	'email'=>str_random(10).'@gmail.com',
        	'password'=>bcrypt('secret')
        ]);
    }

$ php artisan db:seed
> select * from users;
1件追加される

### factory
./database/factories/ModelFactory.php

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

./database/seeds/DatabaseSeeder.php

public function run()
    {
        // $this->call(UsersTableSeeder::class);
        factory(App\User::class, 10)->create();
    }
public function run()
    {
        // $this->call(UsersTableSeeder::class);
        factory(App\User::class, 10)->create()->each(function($user){
        	$user->posts()->save(factory(App\Post::class)->make());
        });
    }

### users以外でfactoryの利用
ModelFactory.php

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'category_id' => $faker->numberBetween(1,0),
        'photo_id' => 1,
        'title' => $faker->sentence(7, 11),
        'body' => $faker->paragraphs(rand(10,15), true),
    ];
});

$ php artisan db:seed

1件だけ追加するならrow sql queryのinsert intoで十分ですが、ページネーションのテストなどでデータ数百件入れたいときなどはFactoryが使えます。

あれ、これ、$fakerって英語だけ?
laravel 5.5以上だと、config/app.phpで’faker_locale’ => ‘ja_JP’,とすると、日本語化されるとのことです。