[英]Solve laravel validation for field with relation
I have some problem where the validation is failing for my blade template with dropdown select on related table. 我有一些问题,其中我的刀片服务器模板的验证失败,并且在相关表上选择了下拉菜单。 I tried to searched for an answer but cannot found it. 我试图搜索答案,但找不到。
To temporarily comment out the the field 'business_unit_id' inside the array in validate function to avoid the error. 暂时将validate函数中数组内部的字段“ business_unit_id”注释掉,以避免错误。
In controller update function: 在控制器更新功能中:
$item = CostCenter::findOrFail($id);
$validatedData = $request->validate([
'code' => 'bail|min:4|required|max:6',
'descr' => 'bail|min:4|required|max:50',
'business_unit_id' => 'required|integer',
]);
$item->fill($validatedData);
$item->business_unit_id = $request->businessUnit;
$item->save();
$request->session()->flash('status', 'Cost centers record was updated!');
return redirect()->route('costCenters.show', ['cost_centers' => $item->id]);
In blade template: 在刀片模板中:
<label for="businessUnit" class="col-sm-2 col-form-label">Business Unit</label>
<select name="businessUnit" class="form-control">
@foreach (App\Models\BusinessUnit::all() as $data)
<option value="{{ $data->id }}"
{{ old('business_unit_id', $cost_centers->business_unit_id ?? '1')
!= $data->id ?: 'selected' }}>
{{ $data->code }} - {{ $data->descr }}
</option>
@endforeach
</select>
The notification received is "The business unit id field is required." 收到的通知是“必须输入业务单位ID字段”。 with my error helper. 与我的错误助手。
$validatedData = $request->validate([
'code' => 'bail|min:4|required|max:6',
'descr' => 'bail|min:4|required|max:50',
'businessUnit' => 'required|integer',
]);
Use businessUnit instead of business_unit_id as we have to use the name of select tag... don't use the id of options tag.. 使用businessUnit代替business_unit_id,因为我们必须使用select标记的名称...不要使用options标记的ID。
you can try this code...and use use keyword to of the code like use Validator; 您可以尝试使用此代码...并在use关键字中使用use关键字,例如use Validator;
$rules = [
'code' => 'bail|min:4|required|max:6',
'descr' => 'bail|min:4|required|max:50',
'businessUnit' => 'required|integer|exists:business_unit,id',
];
$message = [
'code.required' => 'code is required.',
'descr.required' => 'description field is required.',
'businessUnit.required' => 'The business unit id field is required.',
];
$validator = Validator::make($request->all(), $rules,$message);
if ($validator->fails()) {
$arr = array("status"=>400,"msg"=>$validator->errors()-
>first(),"result"=>array());
}
else
{
your code write in this section
}
For any request data validation in controller You can try like this: 对于控制器中的任何请求数据验证,您都可以这样尝试:
$rule=array(
'code' => 'bail|min:4|required|max:6',
'descr' => 'bail|min:4|required|max:50',
'business_unit_id' => 'required|integer',
);
$validator= Validator::make($request->all(),$rule);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.