Not sure if i follow but can't you do $form= new Form($request->except('components')); ?
Validate and Sync multiple objects (checkboxes)
Hello together,
i have a question about validating and storing multiple objects (in this case checkboxes) in Laravel.
Right now, I can have multiple checkboxes in my blade- template and store them into the database without any problems. As soon as I want to validate (over a Validation Request) if approx. one of the checkboxes is checked I cannot save my Object anymore, because I get a: "Array to string conversion" exception. So far I know, that this makes sense. Because the Validation Request returns an array with the values of the "checked" checkboxes.
In this case, I could only use the Validation Request only for validation that approx. one checkbox has a value and add the checkboxes to the model on my own by syncing them, example:
// Save validated data from request
$form= new Form($request->validated());
// unset array of components, because this would not be accepted by the save() Method.
unset($form->components);
auth()->user()->form()->save($form);
// sync the checkboxes
$form->components()->sync($request->components);
I don't think that's pretty clean. How could i avoid to unset $form->components and use the array instead?
StoreFormRequest.php
....
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//'components' => 'min:1',
'components' => 'required',
];
}
...
Form.blade.php
....
<div class="row">
<div class="col-sm">
@foreach($components as $component)
<div class="form-check form-control-lg">
<input class="form-check-input rounded-circle" type="checkbox"
name="components[]"
@if( $form->isComponentChecked($component->id)) checked @endif
@if($readonly) disabled @endif
id="cb{{$component->name}}"
value={{$component->id}}>
<label class="form-check-label" for="cb{{$component->name}}">
{{ $component->name }}
</label>
</div>
@if( is_int($loop->iteration / 4 ))
</div>
<div class="col-sm">
@endif
@endforeach
</div>
</div>
...
Thank you in advance.
Cheers
Please or to participate in this conversation.