Laravel在存储和更新上的表单请求验证使用相同的验证 [英] Laravel form request validation on store and update use same validation
问题描述
我创建了laravel表单验证请求,并且对该验证有唯一的规则.
I create laravel form validation request and have unique rules on that validation.
我想在 store
和 update
方法上使用它,而无需再次创建新的表单请求验证.
I want use it on store
and update
method without create new form request validation again.
但是问题是当 store
上的ID不存在并且验证通过时并且在 update
上执行时,我通过验证失败,因为该ID存在于存储中
but the problem is when on store
the id doesnt exist and the validate is passed
and when on update
i failed the pass the validating because the id is exist on storage
我想忽略 unique
规则上的ID,但使用相同形式的验证请求
i want to ignore the id on unique
rules but use same form validate request
如果通过存储或更新方法执行的此操作忽略唯一ID,则最好的方法是检查表单验证请求类?
what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?
推荐答案
好的.我可以像@porloscerrosΨ建议
Ok.. i can do it like @porloscerros Ψ suggest
public function rules()
{
$rules = [
'name' => 'required|string|unique:products|max:255',
];
if (in_array($this->method(), ['PUT', 'PATCH'])) {
$product = $this->route()->parameter('product');
$rules['name'] = [
'required',
'string',
'max:255',
Rule::unique('loan_products')->ignore($product),
];
}
return $rules;
}
这篇关于Laravel在存储和更新上的表单请求验证使用相同的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!