拉拉维尔 创建用户上的雄辩模型事件



我正在尝试在创建用户时自动为用户创建配置文件。

我正在使用created事件并覆盖boot()方法。但是当我在user->profile->create()上调用create()方法时,它说创建是在null上调用的。我检查了,个人资料在这里是空的。

代码如下:

static::created(function ($user) {
// it returns profile as null, thus create() can't be used on null.
$user->profile->create(['title' => $user->username,]);
});

谁能帮我理解这一点?它在我的导师的代码中工作,他使用的是 Laravel 5.8,但我有 7.1 版。

$user->profile返回相关模型(如果存在(。您必须执行$user->profile(),这将返回查询生成器来查询关系。尝试这样做:

$user->profile()->create(['title' => $user->username,]);

最新更新