User.php 用户注册时多次调用 boot() 方法
User.php boot() method being called multiple times on user registration
在使用内置 Laravel 7 功能创建用户时,我在用户模型上调用了 boot()
方法,以便为新用户分配一个 UUID。我遇到的问题是,由于某种原因,引导方法 get 总共被调用了 4 次,导致在 S3 上创建了 4 个不同的目录。
App/User.php
/**
* Create the user when this class is called
*
* @return void
*/
protected static function boot()
{
// Setup parent
parent::boot();
// Create UUID
$uuid = Str::uuid();
// Create user directory on S3
Storage::disk('s3')->makeDirectory('users/' . $uuid);
// Assign UUID to new user
self::creating(function ($model) use ($uuid) {
$model->id = $uuid;
});
}
这是在创建时向用户添加字段的正确方法吗?我曾尝试使用 RegisterController.php -> create()
方法添加它,但它不会向用户添加任何内容并导致错误提示 ID 需要默认值。
每当要创建 对象 时都会调用 boot 方法(不只是持久化,这是 creating
会做的)。这将在 Laravel 使用 Auth 函数时发生,例如,获取当前用户,因此多次调用启动。
您应该将引导中的所有内容(除了 parent::boot()
调用)放在创建闭包中:
protected static function boot()
{
// Setup parent
parent::boot();
self::creating(function ($model) {
// Create UUID
$uuid = Str::uuid();
// Create user directory on S3
Storage::disk('s3')->makeDirectory('users/' . $uuid);
$model->id = $uuid;
});
}
函数不再需要 use ($uuid)
。
在使用内置 Laravel 7 功能创建用户时,我在用户模型上调用了 boot()
方法,以便为新用户分配一个 UUID。我遇到的问题是,由于某种原因,引导方法 get 总共被调用了 4 次,导致在 S3 上创建了 4 个不同的目录。
App/User.php
/**
* Create the user when this class is called
*
* @return void
*/
protected static function boot()
{
// Setup parent
parent::boot();
// Create UUID
$uuid = Str::uuid();
// Create user directory on S3
Storage::disk('s3')->makeDirectory('users/' . $uuid);
// Assign UUID to new user
self::creating(function ($model) use ($uuid) {
$model->id = $uuid;
});
}
这是在创建时向用户添加字段的正确方法吗?我曾尝试使用 RegisterController.php -> create()
方法添加它,但它不会向用户添加任何内容并导致错误提示 ID 需要默认值。
每当要创建 对象 时都会调用 boot 方法(不只是持久化,这是 creating
会做的)。这将在 Laravel 使用 Auth 函数时发生,例如,获取当前用户,因此多次调用启动。
您应该将引导中的所有内容(除了 parent::boot()
调用)放在创建闭包中:
protected static function boot()
{
// Setup parent
parent::boot();
self::creating(function ($model) {
// Create UUID
$uuid = Str::uuid();
// Create user directory on S3
Storage::disk('s3')->makeDirectory('users/' . $uuid);
$model->id = $uuid;
});
}
函数不再需要 use ($uuid)
。