aikutto
aikutto

Reputation: 592

How to get values of checkbox array in Laravel 5?

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.

Upvotes: 2

Views: 24063

Answers (5)

razan rai
razan rai

Reputation: 1

Though it might not be best practice, here is what I did first of all I send id of a specific model as a value.

<input type="checkbox" id="verify" name="is_varified[]" value="{{$bank->id}}" {{$bank->is_varified == 1 ? 'checked':''}}>

And in controller I added two query to update the field.

//handaling the issue of checkbox
Bank::where("user_id",$user->id)->whereIn('id',$request->is_varified)->update(['is_varified'=> 1]);
Bank::where("user_id",$user->id)->whereNotIn('id',$request->is_varified)->update(['is_varified'=> 0]);

Upvotes: 0

Daniel Orteg&#243;n
Daniel Orteg&#243;n

Reputation: 315

My solution is this for laravel 5

$request->get('is_ok[]');

Upvotes: 0

lewis4u
lewis4u

Reputation: 15047

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; ?>" />

Upvotes: 0

apokryfos
apokryfos

Reputation: 40673

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.

Upvotes: 1

Vaibhavraj Roham
Vaibhavraj Roham

Reputation: 1165

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..

Upvotes: 4

Related Questions