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
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

请教一下大佬,如果是联合唯一索引的 unique 规则 要怎么写呢

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!