Laravel hasone relationship

与世无争的帅哥 提交于 2021-01-29 09:16:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!