Skip to content
Advertisement

how to update a checkbox value on update function on request based?

i written a very simple code to update value of checkbox but it update 1 in db on uncheck it doesnot update 0 if request is submit here is code

<div class="form-group">
    <label>If it is checked it means user can only create given customer order.</label>
    <input type="checkbox" id="js-switch" name="customer_itself" @if($ot->customer_itself == 1) checked @endif>
</div>

controller side

if ($request->has('customer_itself')) {
    if($ot->customer_itself == 1){
        $ot->customer_itself = 0;
    }else{
        $ot->customer_itself = 1;
    }
            

what mistake in it?

Advertisement

Answer

the input type “checkbox” does not return values when unchecked.

Two solutions to choose from :

In PHP :

$ot->customer_itself = $request->has('customer_itself');

In HTML :

Force a first return to “0” to force the update of the database. This value will be overrided if the checkbox is “1” :

<div class="form-group">
    <label>If it is checked it means user can only create given customer order.</label>
    <input type="hidden" name="customer_itself" value=0>
    <input type="checkbox" id="js-switch" name="customer_itself" @if($ot->customer_itself == 1) checked @endif>
</div>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement