当我创建新设备并检查多个复选框时,我有两个具有多对多关系的模型我想将多个voices_id与Device_id一起保存到数据透视表 device_voice
设备控制器(我在编辑功能中遇到此错误未定义变量:selectedVoice)
public function create()
{
$this->authorize("create", Device::class);
$voice_list = Voice::all();
return view('devices.create')
->with('voice_list', $voice_list);
}
public function store(CreateDeviceRequest $request)
{
$this->authorize("create", Device::class);
$input = $request->all();
$voices_checkbox = $input['voice'];
$device = $this->deviceRepository->create($input);
//Device Id and Selected voices is Saved Successfully
$device ->voices()->sync($voices_checkbox);
Flash::success('Device saved successfully.');
return redirect(route('devices.index'));
}
public function edit($id)
{
$device = $this->deviceRepository->findWithoutFail($id);
$this->authorize("update", $device);
$voice_list = Voice::all();
// Here I am getting Device's checked voices, but sinces I am sharing the same Fields Blade with Create and Edit I get this error
//Undefined variable: selectedVoice
$selectedVoice = $device->voices->pluck("id")->toArray();
if (empty($device)) {
Flash::error('Device not found');
return redirect(route('devices.index'));
}
return view('devices.edit')
->with('device', $device)
->with('voice_list', $voice_list)
->with('selectedVoice', $selectedVoice);
}
这是创建和编辑视图的我的字段
<!-- Device Number Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_number', 'Device Number:') !!}
{!! Form::text('device_number', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_name', 'Device Name:') !!}
{!! Form::text('device_name', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('voices_id', 'Voices:') !!}
@foreach ($voice_list as $voice)
{!! Form::checkbox('voice[]', $voice->id, in_array($voice->id, $selectedVoice)) !!}
{!! Form::label('voice', $voice->name) !!}
@endforeach
</div>
<!-- Version Field -->
<div class="form-group col-sm-6">
{!! Form::label('version', 'Version:') !!}
{!! Form::text('version', null) !!}
</div>
谢谢!