Do you want to save the answers in same column as a string or json ? or each answer in new row ?
Feb 13, 2020
8
Level 1
Save multiple checkboxes to the database
view.blade.php
<div class=" ">
<div class="checkbox">
<label class="checkbox">
<input name="q9[]" type="checkbox" value="Diário" />
Diário
</label>
</div>
<div class="checkbox">
<label class="checkbox">
<input name="q9[]" type="checkbox" value="Semanal" />
Semanal
</label>
</div>
<div class="checkbox">
<label class="checkbox">
<input name="q9[]" type="checkbox" value="Quinzenal" />
Quinzenal
</label>
</div>
<div class="checkbox">
<label class="checkbox">
<input name="q9[]" type="checkbox" value="Mensal" />
Mensal
</label>
</div>
<div class="checkbox">
<label class="checkbox">
<input name="q9[]" type="checkbox" value="Outro" />
Outro
</label>
</div>
</div>
</div>
I have some checkbox fields. And I have other radio and input fields.
When trying to save this data in the database, it presents this error
ErrorException: Array to string conversion
public function store(Request $request) {
$data = $request->input();
$data['user_id'] = Auth::id();
Coordenador::create($data);
}
If I remove [] from the field, I will be able to save only one checkbox option in the database. And I wanted to save all the checkbox marked fields. What can I do to fix this array error?
Level 7
User modal
I guess you will have hasMany(Coordenador::class)
by using this line laravel will automatically inject user_id with auth id into cordenator table
$data['q9'] = implode(",",$data['q9']);
auth()->user()->cordenator()->create($data);
or in the way you use
public function store(Request $request) {
$data = $request->input();
$data['user_id'] = Auth::id();
$data['q9'] = implode(",",$data['q9']);
Coordenador::create($data);
}
Please or to participate in this conversation.