Laravel同名多字段自定义验证消息显示异常问题求助
Let's break down how to fix your issue where error messages are either showing on all fields or not showing at all. The core problem is how you're associating error messages with individual array-form fields in both the controller and view.
Step 1: Update the Controller to Return Indexed Error Keys
Instead of using a generic qtys key for your error, use the customer ID as part of the error key (in the format qtys.{customer_id}). This lets Laravel map the error directly to the specific input field.
Modified controller code:
foreach ($request['qtys'] as $key => $val){ if (!$this->_validateMinQty($key, $job, $val)){ $customerTitle = $job->customers()->where('customer_id',$key)->first()->title; // Use qtys.{key} as the error key to target the specific input return redirect()->back()->withErrors([ "qtys.$key" => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle]) ]); } }
Step 2: Update the View to Fetch Indexed Errors
Your current view is checking for a generic qtys error, which is why all fields show the same message when the first one fails. You need to adjust the view to check for the error specific to each customer's input field.
Modified view code:
@foreach($job->customers as $customer) <!-- Update the form-group error class to check for the specific field error --> <div class="form-group {{ $errors->has("qtys.{$customer->id}") ? '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> <!-- Fetch the error for this specific field --> @php ($eleE = $errors->first("qtys.{$customer->id}")) @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
Why This Works
- Controller Change: By using
qtys.$keyas the error key, you're telling Laravel exactly which input field the error belongs to. Laravel's error bag supports nested keys for array inputs, so this maps perfectly to yourqtys[customer_id]form fields. - View Change:
- The
form-groupnow checks if the specific field has an error to apply thehas-errorclass correctly. - The error message fetch uses
$errors->first("qtys.{$customer->id}"), which pulls only the error for that exact input, instead of showing a generic error on all fields.
- The
This way, when a specific customer's quantity fails validation, only that input field will show the error message, and all others remain unaffected.
内容的提问来源于stack exchange,提问作者SaidbakR

