阅读(455) (0)

Laravel 8 写工厂

2021-07-08 16:55:41 更新

首先,请查看应用程序中的 database/factories/UserFactory.php 文件。 开箱即用,此文件包含以下工厂定义:

    namespace Database\Factories;

    use App\Models\User;
    use Illuminate\Database\Eloquent\Factories\Factory;
    use Illuminate\Support\Str;

    class UserFactory extends Factory
    {
        /**
         * The name of the factory's corresponding model.
         *
         * @var string
         */
        protected $model = User::class;

        /**
         * Define the model's default state.
         *
         * @return array
         */
        public function definition()
        {
            return [
                'name' => $this->faker->name,
                'email' => $this->faker->unique()->safeEmail,
                'email_verified_at' => now(),
                'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
                'remember_token' => Str::random(10),
            ];
        }
    } 

如您所见,工厂是最基本的形式,它们是扩展 Laravel 基本工厂类并定义 model 属性和 definition 方法的类。definition 方法返回使用工厂创建模型时应用的默认属性值集。

通过 faker 属性, 工厂可以访问 Faker PHP 函数库, 它允许你便捷的生成各种随机数据来进行测试。

技巧:你也可以在 config/app.php 配置文件中添加 faker_locale 选项来设置 Faker 的语言环境。