【问题标题】:Call to a member function fill() on a non-object在非对象上调用成员函数 fill()
【发布时间】:2014-09-25 08:44:38
【问题描述】:

尝试将信息添加到空的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 已经有信息,则不会出现此问题,并且代码可以正常工作。

【问题讨论】:

  • 你在调用fill()之前初始化新的配置文件吗?
  • 是的,在fill()之前添加了if子句。我已经编辑了代码。

标签: php laravel-4


【解决方案1】:

你可以这样做:

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

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

【讨论】:

  • 有趣,这给了我一个数据库错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'profile' in 'field list' (SQL: update users set updated_at = 2014-09-25 09:05:01, profile = {"firstname":"sdf","lastname":"sd"} where id = 12)
  • 好的,编辑我的答案以反映相关模型的正确保存。
猜你喜欢
  • 2010-09-26
  • 2012-04-20
  • 2015-05-01
  • 2014-08-07
  • 2013-12-01
  • 2015-12-23
  • 2015-08-29
  • 2015-02-02
  • 2015-05-22
相关资源
最近更新 更多