dcat-admin表单值唯一验证(带自定义查询条件使用举例)

此处我以设备号 device_no (硬件唯一识别码,字符串类型)为例:

常规的值唯一验证写法:#

$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();

带自定义查询条件的写法:#

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

$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', '此设备已经被绑定了');
                }
            }
        });
本作品采用《CC 协议》,转载必须注明作者和本文链接
种菜养鱼归山林
mouc
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。