【问题标题】:Laravel Eloquent model events on created user创建用户的 Laravel Eloquent 模型事件
【发布时间】:2020-05-21 10:07:33
【问题描述】:

我正在尝试在创建用户时自动为用户创建个人资料。

我正在使用created 事件并覆盖boot() 方法。但是当我在user->profile->create() 上调用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])
  • 谢谢,这是一个愚蠢的错误。我实际上是 laravel 的新手。

标签: laravel events eloquent profile


【解决方案1】:

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

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

【讨论】:

  • 它的工作,谢谢!我也试过这个,Profile::create(['title' => $user->username, 'user_id' => $user->id]);,但我喜欢它的方式。
  • 没问题,很高兴能帮上忙。如果我有帮助,请尝试标记答案,以便对其他人有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2016-09-11
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多