问题
I am trying to use hasone relation but getting null error. below is my code
User Model:
function profile()
{
$this->hasOne('App\Profile');
}
Profile Model:
function User()
{
return $this->belongsTo('App\User');
}
Register Controller
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
if($user) {
$profile = new Profile();
$profile->name = 'Fake Name';
$profile->father = 'Fake Father';
$user->profile()->save($profile);
}
return $user;
}
Error: Call to a member function save() on null
回答1:
Change User.php to
function profile()
{
return $this->hasOne('App\Profile');
}
You need to return the relationship instance.
来源:https://stackoverflow.com/questions/62422462/laravel-hasone-relationship