php - Laravel 唯一验证在更新时失败
问题描述
我正在使用 laravel 5.7 并使用表单请求,但我的数据库中有一个唯一的 branch_name 以及唯一的 slug,但每次更新验证错误 .branch 名称已经存在
public function rules()
{
switch($this->method()) {
case 'DELETE':
return [
'slug'=>'required',
];
case 'POST':
case 'PUT':
case 'PATCH':
return [
'branch_name'=>'required|max:255|unique:branches,branch_name,id'.$this->id,
'branch_address'=>'required',
];
default:
break;
}
}
我也尝试了以下但没有用
'branch_name'=>'required|max:255|unique:branches,branch_name,'.$this->id,
和
'branch_name'=>'required|max:255|unique:branches,branch_name,slug'.$this->slug,
我对 id 和 slug 都有一个隐藏的值,即使我在规则方法上打印,我也可以看到 id 和 slug
解决方案
这将做:
use Illuminate\Validation\Rule;
'branch_name' => [
'required|max:255',
Rule::unique('branches')->ignore($this->route('branch')),
]
用您的 web.php 编辑路由中的路由参数名称替换“分支”。
您可以在添加和编辑两者中使用此验证。
如果您的数据库字段名称不同,则将该名称作为忽略函数中的第二个参数发送。喜欢
Rule::unique('branches')->ignore($this->route('branch'), 'branchName'),
详细信息:Laraval 验证独一无二
希望这可以帮助。
推荐阅读
- python - 网页抓取后无法从字典中检索值
- node.js - 使用 mongoose 匹配来自 mongodb 的日期文档
- javascript - JSON转换成对象
- javascript - 在 Vue 中将道具从一个步骤传递到另一个步骤(步进器)
- java - 如何使用 JDT 以编程方式编辑全局 Javadoc?
- java - 寻找示例代码以从 aws 参数存储中读取参数值
- excel - 在excel中查找截止日期减去周末的剩余天数
- python - 当未传入数据框时,为什么我能够在函数中更改 Pandas 数据框的值?
- regex - 正则表达式:处理包含嵌套 JSON 对象的 CSV(逗号地狱!)
- pine-script - 我们如何才能使我们的策略只适用于一对特定的货币对?