我的表单中有多个选择列表的数组worker_id[]
,如下所示:
<select multiple class="form-control" name="worker_id[]" size="8">
@foreach($workers as $worker)
<option value= ... </option>
@endforeach
</select>
在我的控制器中,我想在循环中调用函数addRepairWorker
,以便从worker_id
数组中插入值。
if ($request->isMethod('post')) {
$this->validate($request, [
'worker_id' => 'required'
]);
foreach ( arguments ){
$this->repairsService->addRepairWorker($request, $vehicle);
}
}
我需要在foreach
中使用哪些参数?或者还有其他方式吗?
我正在使用Laravel 5。
修改
这是addRepairWorker
函数:
public function addRepairWorker(Request $request , Vehicle $vehicle){
$workers_needed = null;
DB::transaction(function () use ($request, $vehicle, $idcko) {
$workers_needed = new Repair_worker();
$workers_needed->repair_id = $idcko; //$idcko is DB query, not important here
$workers_needed->worker_id = $request->worker_id;
DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)',
[$workers_needed->repair_id, $workers_needed->worker_id]);
});
}
答案 0 :(得分:1)
我会更改函数本身以将任何已分配的worker_id插入到DB
中所以在控制器中
if ($request->isMethod('post')) {
// perform validation
:
// if all validations successful call function
$this->repairsService->addRepairWorker($request, $vehicle);
}
现在该函数将处理多个worker_id值:
public function addRepairWorker(Request $request , Vehicle $vehicle){
$worker_id_array = $request->input('worker_id');
foreach ($worker_id_array as $worker_id) {
DB::transaction(function () use ($request, $vehicle, $idcko) {
$workers_needed = new Repair_worker();
$workers_needed->repair_id = $idcko; //$idcko is DB query, not important here
$workers_needed->worker_id = $worker_id;
DB::insert('insert into repair_worker (repair_id, worker_id) values (?, ?)',
[$workers_needed->repair_id, $workers_needed->worker_id]);
});
}
}
如果您希望该函数也可以作为单个值调用,只需添加一个检查输入是否为数组。
答案 1 :(得分:0)
我不知道repairService的功能是什么,但我认为你正在尝试这个:
public function rules()
{
$rules = array();
if(null !== $this->request->get('worker_id')){
foreach ($this->request->get('worker_id') as $key => $val) {
$rules['worker_id.' . $key] = 'required|integer';
}
}
return $rules;
}
这将为每个多个选定选项传递worker_id和车辆。
编辑:
您的验证也不正确。您不会验证这样的请求数组。
public function addRepairWorker($worker_id , Vehicle $vehicle){
$workers_needed = null;
$workers_needed = new Repair_worker();
$workers_needed->repair_id = $idcko; //$idcko is DB query, not important here
$workers_needed->worker_id = $worker_id;
$workers_needed->save();
编辑2:
USER_DAYS[i] = {
id: json[i].nrC,
date: json[i].dataD,
title: json[i].type,
start: new Date(json[i].startDate),
end: new Date(json[i].endDate),
allDay: true
}