Laravel 具有唯一性的验证规则并与另一列进行比较
Laravel validation rule with unique and compare with another column
我需要一点帮助
这是我的用户 table。我想写一个 laravel 验证规则,就像一个 group_id
应该只有一个用户。例如,另一个名为 John
和 group_id=1
的条目应该给出 The name has already been taken.
错误,但应该插入 john
和 group_id=2
.
*************************** 1. row ***************************
id: 1
name: jhon
group_id: 1
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42
*************************** 2. row ***************************
id: 2
name: michele
group_id: 2
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42
我试过如下,但没有用。谁能帮帮我?
'user.name' => ['required','unique:user,name'.$this->user->id,Rule::unique('user')->where(function ($query) {
return $query->where('group_id', $this->user->group_id);
})],
您可以为此编写自定义验证
'user.name' => ['required',function ($attribute, $value, $fail) {
$user= User::where(function ($query){
$query->where('name',$this->name);
$query->where('group_id',$this->group_id );
})->exists();
if($user){
$fail('User with group already exist');
}
}],
可以参考官方文档
https://laravel.com/docs/8.x/validation#using-closures
更新
'user.name' => ['required',function ($attribute, $value, $fail) {
$user= User::where(function ($query){
$query->where('id','!=',$this->user->id)
$query->where('name',$this->user->name);
$query->where('group_id',$this->user->group_id );
})->exists();
if($user){
$fail('User with group already exist');
}
}],
我需要一点帮助
这是我的用户 table。我想写一个 laravel 验证规则,就像一个 group_id
应该只有一个用户。例如,另一个名为 John
和 group_id=1
的条目应该给出 The name has already been taken.
错误,但应该插入 john
和 group_id=2
.
*************************** 1. row ***************************
id: 1
name: jhon
group_id: 1
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42
*************************** 2. row ***************************
id: 2
name: michele
group_id: 2
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42
我试过如下,但没有用。谁能帮帮我?
'user.name' => ['required','unique:user,name'.$this->user->id,Rule::unique('user')->where(function ($query) {
return $query->where('group_id', $this->user->group_id);
})],
您可以为此编写自定义验证
'user.name' => ['required',function ($attribute, $value, $fail) {
$user= User::where(function ($query){
$query->where('name',$this->name);
$query->where('group_id',$this->group_id );
})->exists();
if($user){
$fail('User with group already exist');
}
}],
可以参考官方文档
https://laravel.com/docs/8.x/validation#using-closures
更新
'user.name' => ['required',function ($attribute, $value, $fail) {
$user= User::where(function ($query){
$query->where('id','!=',$this->user->id)
$query->where('name',$this->user->name);
$query->where('group_id',$this->user->group_id );
})->exists();
if($user){
$fail('User with group already exist');
}
}],