![](/img/trans.png)
[英]Laravel 5.4 Validation Request , How to handle unique validation on update?
[英]In Laravel validation Request, how to handle unique for different colums while update
我有一个用于验证的Employee form
,在更新时我创建了一个验证请求作为EmployeeEdit
,并且在更新 controller 中的员工表单内容时,我传递了这个验证请求来验证数据。
但是员工表格有各种字段,我必须检查不同表格的唯一性。 例如,员工表格有一个 emp_id 字段,我必须检查用户表中的唯一性,手机号码以签入员工表。
如何检查除当前 ID 之外的唯一性。
我在EmployeeEdit Request
中的规则
return [
'emp_id' => 'nullable|max:255|unique:users,'.$this->get('emp_id'),
'code' => 'nullable|unique:employees|max:255'.$this->get('code'),
'mobile_number' => 'required|unique:employees|max:255,'.$this->get('mobile_number'),
];
我的 Controller:
public function doEdit(EmployeeEdit $request, $id)
{
echo "Validation passed";
exit;
}
问题:我不知道如何从请求中传递这些字段,例如 emp_id、mobile_number,以便在当前请求中忽略它们,并且应该检查其他数据的唯一性。
use Illuminate\Validation\Rule;
return [
'emp_id' => [
'nullable',
'max:255',
Rule::unique('users', 'emp_id')->ignore(\Auth::user()->id),
],
];
从@serhii 评论中得到了解决方案
现在在EmployeeEdit Request
中,我添加了(在顶部)
use Illuminate\Validation\Rule;
public function rules()
{
return [
'emp_id' => ['nullable','max:255', Rule::unique('users', 'emp_id')->ignore($this->id)],
'code' => ['nullable','max:255', Rule::unique('employees', 'code')->ignore($this->id,'user_id')],
'mobile_number' => ['nullable','max:255', Rule::unique('employees', 'mobile_number')->ignore($this->id,'user_id')],
注意:由于$this->id
是users
表中的 id,为了在 employees 表中使用它(其中user_id
作为外键),我必须在employees
表规则中显式定义一个列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.