1 回答
TA贡献1820条经验 获得超2个赞
*** 与OP讨论后***
问题应该说明他们正在尝试插入一条记录,并希望验证数据库的唯一性。一种方法是通过自定义规则,如下所示:
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)
],
...
]);
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报