Laravel 多个同名字段的自定义验证消息

Laravel custom validation message for multiple fields with the same name

我在控制器的操作中进行了以下验证:

foreach ($request['qtys'] as $key => $val){
            if (!$this->_validateMinQty($key, $job, $val)){
                $customerTitle = $job->customers()->where('customer_id',$key)->first()->title;
                return redirect()->back()->withErrors(['qtys' => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);
            }
        }

这会检查视图中名为 qtys 的多个表单的输入:

@foreach($job->customers as $customer)

    <div class="form-group {{$errors->first('qtys has-error')}}">
        {!! Form::label('qtys-'.$customer->id, __('Qty').' '.$customer->title) !!}
        <div class="row">
            <div class="col-md-9">
                {!! Form::text('qtys['.$customer->id.']',$customer->pivot->e_production,['class' =>'form-control qtys', "data-sumequal"=>"qty",'required' => 'required','title' => $customer->pivot->aid,'id' => 'qtys-'.$customer->id]) !!}
                <div class="help-block with-errors"></div>
                 @php ($eleE =  $errors->first('qtys'))
                @include('layouts.form-ele-error')
            </div>
            <div class="col-md-3">
                <a href="/storage/create/{{$customer->pivot->aid}}" class="btn btn-nile"><i class="fox-add"></i>{{__('Add Storage')}}</a>
            </div>
        </div>

    </div>
    @endforeach

以上代码有效,但有以下限制:

错误消息在每个名为 qtys[x] 的输入下呈现,其中 x 是一个整数,只有第一个输入 Testana 具有无效数量,如下面的屏幕截图:

在控制器的操作 return 消息中,我尝试使用索引名称作为输入,如下所示:

return redirect()->back()->withErrors(['qtys.10' => ....

但是,它会阻止在任何 qtys 字段下呈现错误消息。有什么解决办法吗?

我找到的解决方案从视图中找到的 definition of first method 开始:

@php ($eleE =  $errors->first('qtys'))

这在我的代码中应更改为:

@php ($eleE =  $errors->first('qtys.'.$customer->id))

因为多个字段都得到了等于客户id的键。 这是我经常使用的技术,当我想在单个 post 或单个表单元素中发送双数据时。 然后在controller中,我保留第一次尝试,

return redirect()->back()->withErrors(['qtys.'.$key => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);

其中 $key 是一个整数。