Laravel中如何验证月份与货币数组的组合唯一性?报错求助
问题解决:Laravel中验证单个字段与数组字段的联合唯一性
问题原因
你当前的验证规则写法错误,Laravel的unique验证器无法直接通过currency.*作为where条件实现单个month字段和currency[]数组的组合唯一性验证,这会触发"undefined offsets"错误。同时原规则中对month的unique设置不符合需求——你需要的是组合唯一,而非month字段本身唯一。
解决方案
步骤1:修正基础验证规则
先移除无效的unique规则,保留核心字段验证逻辑:
$validatedData = Validator::make($request->all(),[ 'month' => 'required|date', 'rate.*' => 'required|numeric|between:0.0001,999.9999', 'currency.*' => 'required|not_in:Choose State/Province', ], [ 'required' => 'This field is required.', 'date' => 'Invalid input. It must be a date', 'numeric' => 'Invalid input. It must be number.', 'between' => 'Invalid input. It must between 0.0001-999.9999', 'not_in' => 'Please select a currency.', ]);
步骤2:添加自定义组合唯一性验证
基础验证通过后,手动遍历currency数组,逐个检查每个货币与月份的组合是否已存在于数据库:
if (!$validatedData->fails()) { $month = $request->input('month'); $currencies = $request->input('currency'); foreach ($currencies as $index => $currency) { // 检查当前货币+月份的组合是否已存在 $exists = DB::table('sap_rate') ->where('month', $month) ->where('currency', $currency) ->exists(); if ($exists) { // 将错误绑定到对应数组项,前端可精准定位报错 $validatedData->errors()->add("currency.$index", 'This record already existed'); } } }
步骤3:保留错误返回逻辑
原有的错误回显逻辑无需修改:
if($validatedData->fails()){ Log::debug('Fails to validate data'); Log::debug('Invalid input'); return redirect()->back()->withInput()->withErrors($validatedData); }
前端错误提示说明
如果是单个货币选择框,原错误提示写法可直接保留:
@error('currency.*') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror
如果是动态生成多个选择框,建议在渲染时使用@error("currency.$index"),确保每个输入框的错误提示精准对应。
内容的提问来源于stack exchange,提问作者Jun Hong
相关产品推荐
相关产品推荐

