How to get values of checkbox array in Laravel 5?

2019-04-17 08:29发布

I created checkboxes in form using javascript:

<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />

When I check 1st and 3rd checkbox and submit the form, Input::get("is_ok") returns me:

['on', 'on']

Is there any way to get value as ['on', null, 'on'] or ['on', 'off', 'on']?

Thanks in advance.

4条回答
祖国的老花朵
2楼-- · 2019-04-17 08:42

I think I have a "good" solution to this (kind of).

<input type="checkbox" name="is_ok[0]" />
<input type="checkbox" name="is_ok[1]" />
<input type="checkbox" name="is_ok[2]" />

(Forced indices here)

In the request:

$array = \Request::get("is_ok") + array_fill(0,3,0);
ksort($array);

This will ensure that (a) The checkbox indices are maintained as expected. (b) the gaps are filled when the request is received.

It's sloppy but may work.

查看更多
时光不老,我们不散
3楼-- · 2019-04-17 08:50

IMHO this is the best practice:

In your migration set that db table field to boolean and default 0

$table->boolean->('is_ok')->default(0);

{!! Form::checkbox('is_ok[]',  false,  isset($model->checkbox) ? : 0) !!}

and if you are not using laravel collective for forms then you can use vanilla php

 <input type="checkbox" name="is_ok[]" value="<?php isset($model->checkbox) ? : 0; ?>" />
查看更多
放我归山
4楼-- · 2019-04-17 08:55

My solution is this for laravel 5

$request->get('is_ok[]');
查看更多
Evening l夕情丶
5楼-- · 2019-04-17 08:59

Hey assign some values to checkboxes like user_id, product_id etc what ever in your application.

E.g. View

<input type="checkbox" name="is_ok[]" value="1" />
<input type="checkbox" name="is_ok[]" value="2" />
<input type="checkbox" name="is_ok[]" value="3" />

E.g. Controller

<?php
    if(isset($_POST['is_ok'])){
        if (is_array($_POST['is_ok'])) {
             foreach($_POST['is_ok'] as $value){
                echo $value;
             }
          } else {
            $value = $_POST['is_ok'];
            echo $value;
       }
   }
?>

You will get array of selected checkbox.

Hope it helps..

查看更多
登录 后发表回答