laravel seeder factory填充数据

时间:2022-10-23 08:40:22

1:/database/factories中UserFactory中修改

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

2:先创建users表的seeder;

php artisan make:seeder UsersTableSeeder


3:在/database/seeds/UsersTableSeeder.php;在run()添加调用user类;生成user表中的10个实例

public function run()
{
factory(\App\User::class,10)->create();
}

4:在DataTableSeeder中call()调用UsersTableSeeder
///database/seeds/DataTableSeeder.php
//是对数据填充限制的操作。所以unguard在前,reguard在后,unguard负责解除自动填充操作限制,reguard负责恢复限制。

public function run()
{
Model::unguard();
App\User::truncate();
$this->call(UsersTableSeeder::class);
Model::reguard();
}

5:生成测试数据

php artisan db:seed //执行所有的seeder
php artisan db:seed --class=你要执行的类名称 //执行某个seeder