Laravel 制造同一型号的工厂时,如何使用型号id?

Laravel 制造同一型号的工厂时,如何使用型号id?,laravel,factory,Laravel,Factory,我尝试在工厂中获取用户id,以便存储哈希版本的用户id: $factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'hashed_id' => Hashids::encode($this->id), 'email' => $faker->unique()->safeEmai

我尝试在工厂中获取用户id,以便存储哈希版本的用户id:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'hashed_id' => Hashids::encode($this->id),
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});
$this->id
'hashed\u id'=>hashid::encode($this->id)
中,假定是指
用户::类

错误

ErrorException:未定义的属性:Illumb\Database\Eloquent\Factory::$id


您应该让观察者跟踪每个数据库记录的创建

这将允许您代理创建和修改数据

见:

或者可以直接向模型上的模型事件添加钩子

protected static function boot()
{
    parent::boot();

    static::creating(function ($user) {
        $user->hashed_id = Hashids::encode($user->id);
    });
}

这让我想到使用模型事件来代替。你可以改变你的答案来包含这个代码:我会给你的。谢谢,我们只是简单地包装了模型事件。我认为您应该使用
created
而不是creating。我尝试使用created,但它不起作用,因为散列的\u id不能为null。那么creating可以为您提供id吗?我不知道,是的!直到我试过才知道以太。我认为这不管用。