You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel项目中如何避免Client Id、Borrower Names及唯一编号重复录入

Laravel 重复数据拦截解决方案

一、数据库层面兜底拦截(必做,最可靠)

直接在数据库表加唯一约束,从根源禁止重复数据写入,不受应用层逻辑影响:

  • 若需单独保证Client Id不重复、单独保证Borrower Names不重复,在对应表的迁移文件中添加字段唯一索引:
// 新增字段时直接加约束
$table->string('client_id')->unique()->comment('客户唯一编号');
$table->string('borrower_names')->unique()->comment('借款人姓名');

// 已有字段后续加约束
$table->unique('client_id');
$table->unique('borrower_names');
  • 若需Client Id和Borrower Names同时重复才禁止录入,添加联合唯一索引:
$table->unique(['client_id', 'borrower_names'], 'idx_client_borrower_unique');

数据库唯一约束触发时会抛出错误码为1062的QueryException,数据不会写入库中。

二、应用层校验(实现友好用户提示)

在数据提交阶段提前校验,避免直接抛出数据库错误,提升使用体验:

1. 表单请求校验(推荐方式)

创建对应业务的FormRequest类,在rules方法中配置唯一校验规则:

单独字段唯一校验规则

public function rules()
{
    return [
        'client_id' => 'required|string|unique:你的业务表名,client_id',
        'borrower_names' => 'required|string|unique:你的业务表名,borrower_names',
    ];
}
// 编辑场景需排除当前数据,将规则修改为:
// 'client_id' => 'required|string|unique:你的业务表名,client_id,' . $this->route('模型变量名'),

组合字段唯一校验规则

use Illuminate\Validation\Rule;

public function rules()
{
    return [
        'client_id' => 'required|string',
        'borrower_names' => [
            'required',
            'string',
            Rule::unique('你的业务表名')
                ->where('client_id', $this->input('client_id'))
                // 编辑场景加此行排除当前数据,新增可删除
                ->ignore($this->route('模型变量名'))
        ]
    ];
}

2. 控制器异常兜底兼容

即使应用层校验漏过,也可在控制器捕获数据库异常返回友好提示:

try {
    // 原有数据存储逻辑
} catch (\Illuminate\Database\QueryException $e) {
    if ($e->errorInfo[1] === 1062) {
        return back()->withInput()->withErrors(['msg' => '录入的客户编号或借款人姓名已存在,请检查后重试']);
    }
    throw $e;
}

内容的提问来源于stack exchange,提问作者Myco S. Kagame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:15:02