Laravel 3 - How to validate checkbox array, for at least 1 checked?

妖精的绣舞 提交于 2019-12-04 11:20:53

Going back on this project and making some more researches, I have found the best way for this problem is the following.

My blade view:

<div class="control-group row-fluid">
    <?php $arrChangeReasons =  Input::old('changeReasons', array()); // array of enable checkboxes in previous request ?>

    <label class="checkbox">{{ Form::checkbox('changeReasons[]', 'certification', in_array('certification', $arrChangeReasons)) }} Certification</label>
    <label class="checkbox">{{ Form::checkbox('changeReasons[]', 'designCorrection', in_array('designCorrection', $arrChangeReasons)) }} Design Correction</label>
</div>

The explanation of the blade view is a 2 steps process, after a validation occur, is the following:

  1. Pull the checkbox array (in my case 'changeReasons[]') with Input::old
  2. From that array we can then search for individual checkbox and see if they are in there, if they are then change the checkbox as a checked state. That is the job of the in_array() function, returning a true/false will change the state of the checkbox.

My controller (REST) code is exactly as it was written in my question at the beginning. For more information, defining $rules = array('changeReasons' => 'required'); will make sure that at least 1 of the checkboxes is checked.

Strernd

Please remember that Checkboxes need a value like . It the Checkbox is checked Input::get('foo') will return 1, but if it is unchecked it will return nothing, because it is not in the post-array.

I'm using this code:

if(Input::get('foo')){
    $bar->is_foo = 1;
}
else{
    $bar->is_foo = 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!