本文介绍了Laravel:验证在更新时是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这个问题已经被问过很多次了,但是没有人解释如何在模型中进行验证时获取ID.
I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.
'email' => 'unique:users,email_address,10'
我的验证规则在模型中,因此如何将记录的ID传递给验证规则.
My validation rule is in the model so how do I pass the ID of the record to the validation rule.
这是我的模型/用户
protected $rules_update = [
'email_address' => 'required|email|unique:users,email_address,'.$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"
];
models/BaseModel
models/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',
..
];
在您的控制器中,操作:更新
In your Controller, action:update
...
$rules = User::$rules;
$rules['email_address'] = $rules['email_address'] . ',id,' . $id;
$validationCertificate = Validator::make($input, $rules);
这篇关于Laravel:验证在更新时是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!