我遇到一些问题,其中我的刀片服务器模板的验证失败,并且在相关表上选择了下拉菜单。我试图搜索答案,但找不到。
要暂时将validate函数中数组内部的“ business_unit_id”字段注释掉,以避免发生错误。
在控制器更新功能中:
$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]);
在刀片模板中:
<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>
收到的通知是“必须输入业务单位ID字段”。和我的错误帮助程序。
答案 0 :(得分:1)
$validatedData = $request->validate([
'code' => 'bail|min:4|required|max:6',
'descr' => 'bail|min:4|required|max:50',
'businessUnit' => 'required|integer',
]);
使用businessUnit代替business_unit_id 因为我们必须使用选择标记的名称... 不要使用选项标签的ID。
答案 1 :(得分:1)
您可以尝试使用此代码...并在代码中使用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
}
答案 2 :(得分:0)
对于控制器中的任何请求数据验证,您可以尝试如下操作:
$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);