Laravel Eloquent 创建用户的模型事件

Laravel Eloquent model events on created user

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

我正在使用 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 returns 相关模型(如果存在)。您必须执行 $user->profile() 其中 returns 一个查询构建器来查询关系。尝试这样做:

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