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 關注
- 177 瀏覽
添加回答
舉報