问题
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