Laravel 用户更新 returns NULL

Laravel User update returns NULL

我正在尝试更新现有的用户模型。

$user = \Auth::user();
$user_data_array = ['email' => 'email@domain.com'];
return $user->update($user_data_array);

执行此代码时,返回值为null,但模型已按预期成功更新。我深入研究了 Illuminate\Database\Eloquent\Model.php,发现 update($attributes, $options) 函数调用了 $this->fill($attributes)->save($options)

当我在 update() 函数中 dd($attributes) 时,$attributes 正确显示为包含电子邮件的数组。但是,当我从 fill() 函数内部 dd($attributes) 时,$attributes 是一个空数组。不知何故,$attributes 似乎迷失在两者之间。

当我尝试使用 save() 函数时,同样的事情发生了。模型更新成功,但是函数returns null.

有没有想过为什么会这样?

代码应如下所示:

<?php
  $user = Auth::user();
  $user->email = "test@test.com";
  return $user->save();
?>

我遇到了同样的问题。

TL;DR;检查 save() 方法是否被覆盖,并确保覆盖方法 returns 是 parent::save()

的结果

在调试 save() 方法时,我记录了要返回的值和返回后的值。 truenull 分别……没有意义。 "Somewhere in the code someone must have overridden the save method and forgot to return parent::save()..."我想但就是找不到。我花了一段时间才意识到这是用于 ACL 的包的特征:https://github.com/Zizaco/entrust。 master 分支中的代码没问题,但我使用的代码来自 1.7.0 版。此版本有此问题,已报告并有拉取请求。

我的用户模型

class User extends Authenticatable
{
    use Notifiable,
        EntrustUserTrait;
}

1.7.0 版的 EntrustUserTrait

trait EntrustUserTrait {
...
    public function save(array $options = [])
    {   //both inserts and updates
        parent::save($options);
        Cache::tags(Config::get('entrust.role_user_table'))->flush();
    }
}

你看到问题了吗?没有 return... 因此 null。因此,要更正此问题,您可以:

public function save(array $options = [])
{   //both inserts and updates
    $saved = parent::save($options);
    Cache::tags(Config::get('entrust.role_user_table'))->flush();
    return $saved;
}