Call to a member function fill() on a non-object

白昼怎懂夜的黑 提交于 2019-12-14 04:18:46

问题


Trying to add information to an empty profile and redirect back.

$user = User::whereUsername($username)->firstOrFail(); // Selects correct user

$input = Input::all(); // a dd($input) at this point confirms input present

$this->profileForm->validate($input); // Passes

$user->profile->fill($input)->save();

return Redirect::route('profile.edit', $user->username);

If $user->profile is null then this gives the error: Call to a member function fill() on a non-object. I tried to remedy this with:

$user = User::whereUsername($username)->firstOrFail(); // Selects correct user

$input = Input::all(); // a dd($input) at this point confirms input present

$this->profileForm->validate($input); // Passes

if ($user->profile == null)
{
    $user->profile = new Profile;
}

$user->profile->fill($input)->save();

return Redirect::route('profile.edit', $user->username);

But in this case it is redirected without adding the profile details ($user->profile is still null at this point).

If $user->profile already has information then this problem does not occur and the code works fine.


回答1:


You can do that like this:

if (count($user->profile))
{   
    $user->profile->fill($input)->save();
}
else
{
    $profile = Profile::create($input);

    $user->profile()->save($profile);
}


来源:https://stackoverflow.com/questions/26034176/call-to-a-member-function-fill-on-a-non-object

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