问题描述
我需要验证字段是否已经存在,引发错误,但是使用此代码不会触发错误
Laravel 7
table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais int
存储方法
$this->validate($request,['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);
也尝试一下
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=',$request->pais);
}),]
];
$this->validate($request,$rules);
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento',]
];
$this->validate($request,$rules);
谢谢!
编辑:
不好,我需要检查两个字段,departamento和idPais,谢谢。
解决方法
这是由于您的字段名称而发生的。唯一规则将尝试查找该列名设置为请求值的记录(在您的情况下为depto
,但您的列名为departamento
)。自定义查询时,您不会覆盖它,而是在此默认行为的基础上添加。来自laravel docs:
默认情况下,唯一规则将检查与要验证的属性名称匹配的列的唯一性。但是,您可以将不同的列名称作为唯一参数的第二个参数传递:
考虑到这一点,您可以更改唯一规则以将列设置为departamento
而不是如下所示的depto
,或更改发送departamento
属性的请求,而不是depto
:
$rules = [
'depto' => [Rule::unique('departamento','departamento')->where(function ($query) use ($request) {
return $query->where('idPais','=',$request->pais);
}),]
];