问题
I have 2 models with Many-to-Many Relation when I create new Device and check multiple Checkboxes I want to save multiple voices_id with Device_id into the Pivot Table device_voice
Device Controller ( I am facing this error Undefined variable: selectedVoice in Edit function )
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);
}
This is My Fields for Both Create and Edit Views
<!-- 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>
Thanks!
回答1:
Use the sync() method:
$device->voices()->sync($request->voices);
来源:https://stackoverflow.com/questions/42532629/how-to-save-multiple-checkboxes-value-into-pivot-table