I have a checkbox field in my form, I want to insert data to database if the checkbox is checked and delete the data in database if the checkbox is unchecked.
Here is my checkbox code:
<ul class="list-unstyled mb-0">
@foreach ($companies as $company)
<li class="d-inline-block mr-2 mb-1">
<fieldset>
<div class="checkbox">
<input type="checkbox" name="company_id[]"
class="checkbox-input" value="{{ $company->id }}"
id="{{ $company->id }}"
@foreach ($supervisor_company as $spv)
@if ($spv != null)
@if ($spv->company_id == $company->id)
checked
@endif
@endif
@endforeach>
<label for="{{ $company->id }}">{{ $company->name }}</label>
</div>
</fieldset>
</li>
<li class="d-inline-block mr-2 mb-1">
@endforeach
</ul>
And this is my controller:
if ($request->has('company_id')) {
foreach ($request->company_id as $key => $company) {
$spv_data = EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->first();
if ($spv_data != null) {
EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->update(['company_id' => $company]);
} else {
$emp_spv = new EmployeeSpvCompany;
$emp_spv->employee_id = $employee_id;
$emp_spv->company_id = $company;
$emp_spv->save();
}
}
}
Insert to database if the checkbox is checked is already working, but I don't know how to delete the data in database if the checkbox is unchecked
updateOrCreatemethod (assuming you are only expecting to be updating 1 record) but you are not actually updating any field