У меня есть 2 модели с отношением «Множество ко многим», когда я создаю новое устройство и проверяю несколько флажков. Я хочу сохранить несколько voices_id с помощью Device_id в сводной таблице device_voice
Device Controller (я столкнулся с этой ошибкой Неопределенная переменная: 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>
Благодаря!
Используйте метод sync()
:
$device->voices()->sync($request->voices);