如何将多个复选框值保存到数据透视表中?

问题描述:

当我创建新设备并检查多个复选框时,我有两个具有多对多关系的模型我想用Device_id将多个voices_id保存到数据透视表中 device_voice

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

设备控制器(我正在面对这个错误未定义的变量:selectedVoice在编辑功能)

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>

谢谢!

使用 sync() 方法:

$device->voices()->sync($request->voices);