How to save multiple Checkboxes value into Pivot Table?

我们两清 提交于 2020-01-15 05:02:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!