简体   繁体   中英

Update checkbox values in database

What is the best way to update records send from checkbox form. How to get to known which one have been unchecked.

My algorithm unset all values than goes again and check ids from request. Moreover it cause problem with timestamps, because all values are being updated every single time.

public function plansUpdate(Request $request){
        //set all plans as not default to handle unchecked
        $plans = $this->planService->getAllPlans()->pluck('id');
        PlanModel::whereIn('id', $plans)->update(['is_default' => false]);

        //set checked plans as default
        $defaultPlans = $request->get('default-plans');
        PlanModel::whereIn('id', $defaultPlans)->update(['is_default' => true]);

        return redirect()->back();
    }

I would like to perform better solution where only values changed in the form are being "touch" in the back-end.

Create it like this, don't forget to replace $id with the actual ID:

<input type="hidden" name="default_plans[$id]" value="0" />
<input type="checkbox" name="default_plains[$id]" value="1" />

Then in your php code iterate over the models and update them in transaction.

public function plansUpdate(Request $requets) {
    $plans = $this->planService->getAllPlans();

    $defaultPlans = $request->get('default_plans');
    DB::beginTransaction();
    foreach($plans as $plan) {
        $plan->is_default = boolval($defaultPlans[$plan->id] ?? false);
        $plan->save();
    }
    DB::commit(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM