Ilya Davydyuk Ilya Davydyuk - 6 months ago 47
PHP Question

Laravel 5.2, error on empty array

Simple situation. Multiple checkboxes:

<input name="check1[]" type="checkbox" class="magic-checkbox" value="value1_1"/>
<input name="check1[]" type="checkbox" class="magic-checkbox" value="value1_2"/>

<input name="check2[]" type="checkbox" class="magic-checkbox" value="value2_1"/>
<input name="check2[]" type="checkbox" class="magic-checkbox" value="value2_2"/>

It saves, and than i make a check if checkbox checked. Array in controller:

$checkboxes_array = array_merge($ch->check1, $ch->check2);

So, if "check2" checkboxes are not checked - i get an error:

ErrorException in adFormController.php line 70:

How to fix it?


Basically at some point you need to check if the request has the input with that name. In this case:

  $ch->check1 = [0,0];
  $ch->check2 = [0,0];

The way you checked them is prone to braking, because, in your case, $ch->check2 is not set. Try dumping dd($ch->check2) before the array_merge.