I'm trying to automatically create a profile for a user when a user is created.
I'm using the created
event and overriding the boot()
method. But I when call the create()
method on user->profile->create()
, it says create was called on null. I checked and profile is null in this.
Here's the code:
static::created(function ($user) {
// it returns profile as null, thus create() can't be used on null.
$user->profile->create(['title' => $user->username,]);
});
Can anyone help me understand this? It's working in my tutor's code, and he is using Laravel 5.8 but I have version 7.1.
$user->profile
returns the related model if any exists. You have to do $user->profile()
which returns a query builder to query the relation. Try to do it like so:
$user->profile()->create(['title' => $user->username,]);