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

Laravel多列不区分大小写唯一验证规则简化实现问询

简洁实现dc_name和dc_code组合唯一且忽略大小写的表单验证

方案1:复用内置Unique规则(最简洁)

把组合唯一的验证逻辑抽成变量,同时应用到两个字段上,避免重复编写代码:

// 定义组合唯一验证规则,处理大小写不敏感匹配
$uniqueDcCombination = Rule::unique('dcs')
    ->whereRaw('LOWER(dc_name) = ?', [strtolower(request('dc_name'))])
    ->whereRaw('LOWER(dc_code) = ?', [strtolower(request('dc_code'))]);

// 执行表单验证
$data = request()->validate([
    'dc_name' => ['required', $uniqueDcCombination],
    'dc_code' => ['required', $uniqueDcCombination]
]);

这里利用Laravel内置的Rule::unique,通过whereRaw直接执行大小写转换的SQL匹配,同时将规则抽为变量复用,无需重复编写闭包逻辑。

方案2:自定义验证规则(高复用性)

如果这个组合验证需要在多个接口或场景中使用,建议封装成自定义规则类,便于后续维护:

  1. 创建App\Rules\UniqueDcCombination规则类:
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class UniqueDcCombination implements Rule
{
    private $inputName;
    private $inputCode;

    // 可选传入字段值,适配不同验证场景
    public function __construct($name = null, $code = null)
    {
        $this->inputName = $name;
        $this->inputCode = $code;
    }

    public function passes($attribute, $value)
    {
        // 优先使用传入值,否则从请求中获取对应字段
        $dcName = $this->inputName ?? request('dc_name');
        $dcCode = $this->inputCode ?? $value;

        // 检查组合是否唯一(忽略大小写)
        return !DB::table('dcs')
            ->whereRaw('LOWER(dc_name) = ?', [strtolower($dcName)])
            ->whereRaw('LOWER(dc_code) = ?', [strtolower($dcCode)])
            ->exists();
    }

    public function message()
    {
        return 'DC名称与编码的组合必须唯一。';
    }
}
  1. 在验证逻辑中使用该规则:
use App\Rules\UniqueDcCombination;

$data = request()->validate([
    'dc_name' => ['required', new UniqueDcCombination(request('dc_name'))],
    'dc_code' => ['required', new UniqueDcCombination()]
]);

这种方式将验证逻辑集中管理,后续修改规则只需调整自定义类,无需在多个验证点重复修改。

注意事项

  • 两种方案均通过SQL的LOWER()函数统一转换为小写进行匹配,确保大小写不敏感的唯一性校验。
  • 若为更新操作,需要排除当前记录,可在Rule::unique后追加->ignore($recordId),或在自定义规则的passes方法中添加排除条件。

内容的提问来源于stack exchange,提问作者Hrushikesh Vartak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:22:09