常规的值唯一验证写法

$table = $form->repository()->model()->getTable();
$connection = config('admin.database.connection');
$id = $form->getKey();

$form->text('device_no')->required()
            ->creationRules(['required', "unique:{$connection}.{$table}"])
            ->updateRules(['required', "unique:{$connection}.{$table},device_no,$id"])->width(6)->required();

带自定义查询条件的写法

$form->submitted(function (Form $form) {
            if ($form->isCreating()) {
                if (DeviceInfo::where('device_no', $form->device_no)->where('yard_id', '>', '0')->exists()) {
                    $form->responseValidationMessages('device_no', '此设备已经被绑定了');
                }
            } elseif ($form->isEditing()) {
                if (DeviceInfo::where('device_no', $form->device_no)->where('yard_id', '>', '0')->where('id', '!=', $form->model()->id)->exists()) {
                    $form->responseValidationMessages('device_no', '此设备已经被绑定了');
                }
            }
        });

在提交前检查回调里定义,(注意 where 方法参数),搭配 responseValidationMessages 方法在表单对应 input 里提示验证错误。

原文发表于:https://learnku.com/articles/62867