php – Laravel:验证在更新时是唯一的

前端之家收集整理的这篇文章主要介绍了php – Laravel:验证在更新时是唯一的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这个问题已经被问过很多次了,但没有人会解释如何在模型中验证ID.
'email' => 'unique:users,email_address,10'

我的验证规则在模型中,所以如何将记录的ID传递给验证规则.

这是我的型号/用户

protected $rules_update = [
    'email_address' => 'required|email|unique:users,'.$id,'first_name' => "required",'last_name' => "required",'password' => "required|min:6|same:password_confirm",'password_confirm' => "required:min:6|same:password",'password_current' => "required:min:6"
];

车型/ BaseModel

protected $rules = array();

public $errors;

/*
    * @data: array,Data to be validated
    * @rules: string,rule name in model 
*/

public function validate($data,$rules = "rules") {

    $validation  = Validator::make($data,$this->$rules);

    if($validation->passes()) {
        return true;
    }

    $this->errors = $validation->messages();

    return false;
}
一个简单的方案.

在你的模型

protected $rules = [
    'email_address' => 'sometimes|required|email|unique:users',..
];

在您的控制器中,操作:更新

...
$rules = User::$rules;
$rules['email_address'] = $rules['email_address'] . ',id,' . $id;
$validationCertificate  = Validator::make($input,$rules);

猜你在找的Laravel相关文章