Laravel模型:仅更新一个字段

时间:2014-03-27 11:53:13

标签: php laravel

我的模型有验证规则:

protected $fillable = array('username','firstname','lastname',"street","city","country","birthday","email");

public static $rules = array(
    'username' => 'required|between:4,16|unique:users',
    'email' => 'required|email|unique:users',
    'password' => 'required|min:4',
    'firstname' => 'required|alpha_num|between:2,16',
    'lastname' => 'required|alpha_num|between:2,32',
);

和我的更新方法:

public function update($id)
{
    $user = User::find($id);        
    $data = Input::all();       
    if ( isset($data['firstname']) ) {
        $user->firstname = $data['firstname'];
    }

    $success = $user->update();

    if ( $success ) {
        return Response::json(array('error' => false, 'user' => $user->toArray()), 200 );
    } else {
        return Response::json(array('error' => true, 'message' => $user->errors()->all()), 400 );   
    }
}

现在我收到了一个错误:

 {
    "error": true,
    "message": [
        "The username has already been taken.",
        "The email has already been taken."
    ]
}

所以,问题是:我如何只更新模型的一个字段?

更新

当我使用Ardent(https://github.com/laravelbook/ardent)时,我可以这样做:

$success = $user->updateUniques();

现在一切正常。

2 个答案:

答案 0 :(得分:2)

错误消息表明,在更新模型时,验证唯一要求会检测到用户名和电子邮件已存在。为避免这种情况,请将当前更新的id实例附加到make验证器。在验证器中使用参数来检测您是在更新还是创建它,并在第一种情况下发送用户ID,然后您可以使用:

强制唯一规则忽略给定ID

'username' => 'required|between:4,16|unique:users,'.$userId,
'email' => 'required|email|unique:users,'.$userId,

此处提供更多详细信息:https://stackoverflow.com/a/22406205/1165509

答案 1 :(得分:0)

protected function setConditionalRules($model)
{
    $id = $model->getKey();
    foreach(['email', 'username'] as $field)
    {
        $this->validator->sometimes($field, $this->rules[$field].",$id", function($input) use($model, $field)
        {
            if($model->exists)
            {
                $this->validator->setRules(array_except($this->validator->getRules(), [$field]));
                return true;
            }
            return false;
        });
    }

}