调用非对象上的成员函数fill()


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

尝试将信息添加到空的profile并重定向回。

$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);

如果$user->profilenull,则这给出错误:Call to a member function fill() on a non-object。我试着用来补救这个问题

$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);

但在这种情况下,它被重定向而不添加配置文件详细信息(此时$user->profile仍然是null)。

如果$user->profile已经有信息,那么这个问题就不会发生,并且代码运行良好。

您可以这样做:

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