Home > Mobile >  Delete record in database if checkbox is unchecked
Delete record in database if checkbox is unchecked

Time:01-06

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 >
   @foreach ($companies as $company)
   <li >
      <fieldset>
         <div >
            <input type="checkbox" name="company_id[]"
             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 >
      @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

CodePudding user response:

I expect the company_id field is a multi-select type so the value will be returned in the form of an array. I guess the following code will work in this situation.

$companyIds = $request->has('company_id'); // [1, 2]

if ($companyIds) {
    foreach ($companyIds as $company_id) {
        $employeeSpvCompanyInstance = EmployeeSpvCompany::firstOrCreate([
            'employee_id' => $employee_id,
            'company_id' => $company_id
        ]);
    }
    EmployeeSpvCompany::where('employee_id', $employee_id)->whereNotIn('company_id', $companyIds)->delete();
} else {
    EmployeeSpvCompany::where('employee_id', $employee_id)->delete();
}

CodePudding user response:

Ah!! I found something called whereNotIn. I just need to check if the data is not in my array request.

EmployeeSpvCompany::whereNotIn('company_id', $request->company_id)->delete();
  •  Tags:  
  • Related