我有subject
个表,而字段分别是standard_id
,stream_id
,medium_id
,board_id
,subject_name
等。
我想为subject_name
添加唯一的规则,该规则对于standard_id
,stream_id
,medium_id
,board_id
字段是唯一的。
$validator = Validator::make( $inputs,
[
'v_name' => [
'required',
Rule::unique( 'tbl_subject' )->ignore( $id, 'id' ),
],
],
[
'v_name.required' => 'Name is required',
'unique' => 'Name address already exits.',
]
);
示例
standard_id
,stream_id
,medium_id
,board_id
subject_name
1 2 1 3 A
3 2 4 1 B
1 3 1 4 c
验证是否就像subject_name“ A”对于1,2,1,3是唯一的。B对于3,2,4,1是唯一的。 但是subject_name“ A”对于2,2,1,3等不是唯一的。
答案 0 :(得分:4)
***与OP讨论后***
该问题应该表明他们正在尝试插入单个记录,并且想要针对数据库验证唯一性。一种方法是通过custom rule,如下所示:
class UniqueSubject implements Rule
{
private $keys;
public function __construct(array $keys) {
$this->keys = $keys;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return ! Subject::where($this->keys)->where('subject_name', $value)->exists();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The Subject Name must be unique for the given standard, stream, medium and board.';
}
}
然后,您可以在规则中使用验证,例如:
$keys = $request->only('i_standard_id', 'i_stream_id', 'i_board_id', 'i_medium_id');
$validator = Validator::make( $inputs, [
...
'subject_name' => [
'required',
'string',
new UniqueSubject($keys)
],
...
]);