Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

checkbox stores 0 whatever value the user enters

I am using data-bootstrap-switch checkbox in dynamic input field

Controller:

public function store(StoreLeaveTypeRequest $request)
{ 
    $leavetype = new HrLeaveType();
    $leavetype->leave_type_name             = $request->leave_type_name;
    $leavetype->leave_type_code             = $request->leave_type_code;

   $leavetype->save();        

    foreach ($request->employee_type_id as $key => $employee_type_id){

   $insert_array = [
        'employee_type_id'                  => $request->employee_type_id[$key],    
        'weekend_inclusive'                 => $request->weekend_inclusive[$key] ?? 0,
        'holiday_inclusive'                 => $request->holiday_inclusive[$key] ?? 0,
        'leave_type_id'                     => $leavetype->id,
     ];

      HrLeaveTypeDetail::create($insert_array );

       } 
    }

view

   <form  action="{{route('leave.leave_types.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}
       
       
       <div class="card-body">
        <div class="form-body">
        <div class="row">  
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Leave Type Name:<span style="color:red;">*</span></label>
              <input  type="text" name="leave_type_name" value="{{ old('leave_type_name', $leavetype->leave_type_name) }}" placeholder="Enter leave type name" class="form-control @error('leave_type_name') is-invalid @enderror">
                @error('leave_type_name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror                 
            </div>
          </div>

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Leave Type Code:</label>
              <input  type="text" name="leave_type_code" value="{{ old('leave_type_code', $leavetype->leave_type_code) }}" placeholder="Enter leave typecode" class="form-control @error('leave_type_code') is-invalid @enderror">
                @error('leave_type_code')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror                 
            </div>
          </div>                
            
            
          <div class="col-sm-12">
            <div class="form-group">
                <label>Description</label>
                <textarea rows="2" name="description" class="form-control @error('description') is-invalid @enderror" value="{{old('description',$leavetype->description)}}" placeholder="Enter Description here ...">{{old('description',$leavetype->description)}}</textarea>
                @error('description')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror                 
            </div>
          </div>

   <div class="col-sm-12">
            <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">Employee Type<span style="color:red;">*</span></th>
                            <th scope="col">Weekend Inclusive</th>
                            <th scope="col">Holiday Inclusive</th>   
                            <th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td width="40%">                    
                                <select class="form-control select2bs4" data-placeholder="Select Employee Type" tabindex="1" name="employee_type_id[]">
                                    <option value="0" selected="true" disabled="true">Select Employee Type</option>
                                     @if($employeetypes->count() > 0 )
                                        @foreach($employeetypes as $employeetype)
                                         <option name="employee_type_id[]"  value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>
                                        @endforeach
                                    @endif                                         
                                </select>
                            </td>                                                         
                            <td width="10%"><input type="checkbox" name="weekend_inclusive[]"  class="form-control weekend_inclusive" value="{{old('weekend_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>
                            <td width="10%"><input type="checkbox" name="holiday_inclusive[]"  class="form-control holiday_inclusive" value="{{old('holiday_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>                                
                            <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
                         </tr>
                        </tbody>
                    </table>
        </div>
       </div>
     </div>
    </div>          
    <!-- /.card-body -->
    <div class="card-footer">
      <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
    </div>

jQuery

<script type="text/javascript">
    $(document).ready(function(){
        $('.addRow').on('click', function () {
            addRow();

        });
        function addRow() {
            var addRow = '<tr>\n' +
'   <td width="40%"><select class="form-control select2bs4" data-placeholder="Choose Employee Type" tabindex="1" name="employee_type_id[]">\n' +
       '             <option value="0" selected="true" disabled="true">Select Employee Type</option>\n' +
       '              @if($employeetypes->count() > 0 )\n' +
       '                 @foreach($employeetypes as $employeetype)\n' +
       '                 <option value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>\n' +
        '                 @endforeach\n' +
        '             @endif\n' +
        '         </select></td>\n' +
        '        <td width="10%"><input type="checkbox" name="weekend_inclusive[]" class="form-control weekend_inclusive" value="{{old('weekend_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>\n' +
       '        <td width="10%"><input type="checkbox" name="holiday_inclusive[]" class="form-control holiday_inclusive" value="{{old('holiday_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>\n' +
'   <td width="5%"><a   class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
'         </tr>';
            $('tbody').append(addRow);
            addRemoveListener();
        };
    addRemoveListener();
 });
</script>

I am using bootstrap switch checkbox. The checkbox can either be 0 or 1

0=No and 1=Yes

I am using dynamic input fields. When I submitted, What I observed is that whatever the user selects for:

    weekend_inclusive
    holiday_inclusive

the application stores 0 for both:

    weekend_inclusive
    holiday_inclusive

How do I resolve this?

0 likes
46 replies
MichalOravec's avatar

For checkbox you need to use has

'weekend_inclusive' => $request->has('weekend_inclusive.'.$key)
Snapey's avatar

way too much code as usual

All that is needed to show is the request content and the controller method. What you do in the view is a separate issue if you cannot see 0 and 1 being passed to the controller.

noblemfd's avatar

@michaloravec - I don't just understand what is going on. At times, it saves 1 or 0 irrespective of what the user selects. What am I doing wrongly

jlrdw's avatar

@noblemfd if a checkbox is not checked, nothing is passed. Therefore you use "has".

  • If it does not exist in request you store a 0
  • If it does exist in request you store a 1

I usually just do this:

$yourcheck = !empty(Request::input('yourcheck')) ? 1 : 0;

Works same as has.

noblemfd's avatar

@jlrdw - Is this the right way I should have written the checkboxes in the view:

     <td width="10%"><input type="checkbox" name="weekend_inclusive[]"  class="form-control weekend_inclusive" value="{{old('weekend_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>
     <td width="10%"><input type="checkbox" name="holiday_inclusive[]"  class="form-control holiday_inclusive" value="{{old('holiday_inclusive') ? 'checked' : '' }}" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>

especially here:

value="{{old('holiday_inclusive') ? 'checked' : '' }}"
Snapey's avatar

you cannot use old() with field names that use array [] unless you also use dotted notation in the old command

but that is a separate issue to your question

jlrdw's avatar

@snapey what do you mean by without dot notation, so far I have never needed dot notation.

 {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}"{{ ( is_array(old('likes')) && in_array($v, old('likes')) ) ? 'checked ' : '' }}  />

Which is enclosed in a foreach loop.

Snapey's avatar

because you are using in_array. I don't see that in the OP code

noblemfd's avatar

@jlrdw - since I already have the foreach statement in the controller where is $v coming from in

 {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}"{{ ( is_array(old('likes')) && in_array($v, old('likes')) ) ? 'checked ' : '' }}  />
jlrdw's avatar

@noblemfd the point is when you foreach over a checkbox array you have to compare against known possible values.

Okay I see it's not checkbox array, from snapey next reply.

Snapey's avatar

not relevant to the problem

He does not have an array of checkboxes, he has a group of fields that is repeated

jlrdw's avatar
      'weekend_inclusive'         => !empty($request->weekend_inclusive) ? 1 : 0;

I use facade so I would:

     'weekend_inclusive'         => !empty(Request::input('weekend_inclusive')) ? 1 : 0;

If these are individual checkboxes, why do you have the brackets? []

Tack on the key [$key] if needed, sorry your form is hard to read.

Snapey's avatar

@jlrdw

why do you have the brackets? []

because they have a dynamic form, adding a number of rows as required, each having radios

jlrdw's avatar

Maybe try one with some checked and some not checked and

dd($request->weekend_inclusive);

See what you get, show here.

noblemfd's avatar

@jlrdw - dd($request->weekend_inclusive[$key]);

gives null

but when I did !empty($request->weekend_inclusive) ? 1 : 0,

it assigns 1 irrespective of the values

noblemfd's avatar

@jlrdw - I got this error ERROR: ErrorException: Undefined offset: 2 in C:\xampp\htdocs\myapp\app\Http\Controllers\Leave\LeaveTypesController.php:98 when I did $request->weekend_inclusive[$key] ? 1 : 0; and it points to:

'holiday_inclusive' => $request->holiday_inclusive[$key] ? 1 : 0,
Snapey's avatar

pity you are no further than my very first reply, which you have still not followed

anyway, your design is fundamentally flawed because of the way you key the data

say you have 5 rows, the checkbox is only checked on the fourth row

since only checked inputs are actually sent, your array of checkboxes only contains one member and you have no idea which table row it belongs to

noblemfd's avatar

@snapey - When the view page is rendered, it loads only one row. But the addRow() is used in the jquery to dynamically add other rows. I've been on this for days and the issue is still there. Is there a better way to do it. I don't mind to remove everything I have done earlier.

The error is still:

production.ERROR: ErrorException: Undefined offset: 1 in C:\xampp\htdocs\myapp\app\Http\Controllers\Leave\LeaveTypesController.php:98

and this points to :

$request->weekend_inclusive[$key] ? 1 : 0; and 'holiday_inclusive' => $request->holiday_inclusive[$key] ? 1 : 0,

When I dd(HrLeaveTypeDetail::create($insert_array )); I got this in the first row, whatever the values of :

weekend_inclusive and holiday_inclusive

dd(HrLeaveTypeDetail::create($insert_array ));

gives:

  #attributes: array:8 [▼
    "no_of_days" => "30"
    "employee_type_id" => "2"
    "weekend_inclusive" => 1
    "holiday_inclusive" => 1
    "leave_applicable_gender" => "1"
    "leave_type_id" => 4
    "company_id" => 1
    "id" => 5
  ]
  #original: array:8 [▼
    "no_of_days" => "30"
    "employee_type_id" => "2"
    "weekend_inclusive" => 1
    "holiday_inclusive" => 1
    "leave_applicable_gender" => "1"
    "leave_type_id" => 4
   "company_id" => 1
    "id" => 5
]

Kindly assist.

Snapey's avatar

You should change the way you name the form elements.

Consider instead, fields called

name="leavetype[]employeetype"

name="leavetype[]weekendinclusive"

name="leavetype[]holidayinclusive"

Then you will get an array where each member of the array represents one row of your table

You can then tell if the checkbox on row two is checked or unchecked.

Remove all your old() helpers to start with - especially within the dynamic added row where it can never be used,

noblemfd's avatar

@snapey - Sorry if my questions annoy you. What do you mean by:

name="leavetype[]employeetype"

name="leavetype[]weekendinclusive"

name="leavetype[]holidayinclusive"

I have removed the old() helpers, and I now have:

            <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">Employee Type<span style="color:red;">*</span></th>
                            <th scope="col">Weekend Inclusive</th>
                            <th scope="col">Holiday Inclusive</th>   
                            <th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td width="40%">                    
                                <select class="form-control select2bs4" data-placeholder="Select Employee Type" tabindex="1" name="employee_type_id[]">
                                    <option value="0" selected="true" disabled="true">Select Employee Type</option>
                                     @if($employeetypes->count() > 0 )
                                        @foreach($employeetypes as $employeetype)
                                         <option name="employee_type_id[]"  value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>
                                        @endforeach
                                    @endif                                         
                                </select>                                    
                            </td>                                                          
                            <td width="10%"><input type="checkbox" name="weekend_inclusive[]"  class="form-control weekend_inclusive" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>
                            <td width="10%"><input type="checkbox" name="holiday_inclusive[]"  class="form-control holiday_inclusive" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>                                
                            <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
                         </tr>
                        </tbody>
                    </table>

But the error is still there. Or is not even possible to remove the addRow() and just load based on the count of employee_type_id. If there are 4 employee_type_id, then it loads 4 rows without the jquery.

What else do I do?

Snapey's avatar

change the names of the form fields as suggested.

for example;

<input type="checkbox" name="leavetype[]weekend_inclusive"  class="form-control weekend_inclusive" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES">
noblemfd's avatar

@snapey - When I changed it to:

            <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">Employee Type<span style="color:red;">*</span></th>
                            <th scope="col">Weekend Inclusive</th>
                            <th scope="col">Holiday Inclusive</th>   
                            <th scope="col"><a class="btn btn-info addRow"><i class="fa fa-plus"></i></a></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td width="40%">                    
                                <select class="form-control select2bs4" data-placeholder="Select Employee Type" tabindex="1" name="leavetype[]employee_type_id">
                                    <option value="0" selected="true" disabled="true">Select Employee Type</option>
                                     @if($employeetypes->count() > 0 )
                                        @foreach($employeetypes as $employeetype)
                                         <option name="employee_type_id[]"  value="{{$employeetype->id}}">{{$employeetype->employee_type_name}}</option>
                                        @endforeach
                                    @endif                                         
                                </select>                                    
                            </td>                                                         
                            <td width="10%"><input type="checkbox" name="leavetype[]weekend_inclusive"  class="form-control weekend_inclusive" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>
                            <td width="10%"><input type="checkbox" name="leavetype[]holiday_inclusive"  class="form-control holiday_inclusive" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES"></td>                                
                            <td width="5%"><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
                         </tr>
                        </tbody>
                    </table>

I got the validation error that Employee Type is required.

That means it's not more seeing the fields. This is the request rules I used for validation

public function rules()
{
    return [        
        'employee_type_id'           => 'required|array', 
        'employee_type_id.*' => [
             'required',           
        ],                          
    ];
}

Or could it be because $leavetype is not for the array

public function store(StoreLeaveTypeRequest $request)
{
     $leavetype = new HrLeaveType();
     $leavetype->leave_type_name             = $request->leave_type_name;
     $leavetype->leave_type_code             = $request->leave_type_code;

    $leavetype->save();        

    foreach ($request->employee_type_id as $key => $employee_type_id){
    $insert_array = [
         'employee_type_id'                  => $request->employee_type_id[$key],    
         'weekend_inclusive'                 => $request->weekend_inclusive[$key] ? 1 : 0,
          'holiday_inclusive'                => $request->holiday_inclusive[$key] ? 1 : 0,
         'leave_type_id'                     => $leavetype->id,

        ];
 }
Snapey's avatar

Yes, you have to change EVERYTHING because the data is coming from the form in a different format

Snapey's avatar

dd($request->all()) at the top of the controller method so that you can be sure of the format of the data

noblemfd's avatar

@snapey - I deliberately entered 4 rows. When I dd($request->all()), I got:

array:10 [▼
  "_token" => "WIpLTnxM3D1WzGd7viU0DlHtTfRpQclOXkWf5JB0"
  "leave_type_name" => "Annual Leave"
  "leave_type_code" => "wqwqw"
  "employee_type_id" => array:4 [▼
    0 => "1"
    1 => "2"
    2 => "5"
    3 => "6"
  ]
  "weekend_inclusive" => array:2 [▼
    0 => "on"
    1 => "on"
  ]
  "holiday_inclusive" => array:2 [▼
    0 => "on"
    1 => "on"
  ]
]
  1. I observed that the rest takes 4 rows except weekend_inclusive and holiday_inclusive that has two.

  2. 0 and 1 are both on as in 0 => "on" 1 => "on"

Next

Please or to participate in this conversation.