0

I have a survey form and I need to put the value in one column based on checkbox value.

My input form for the checkbox:

<input type="checkbox" name="chk" value="1" />
<label for="chk[]">Prijava</label>

Controller:

public function store(Request $request)
    {
        $validated=$request->validate([
            'title'=>'required',
            'description'=>'nullable'
        ]);
        if(Input::get('chk')==="1"){
            $validated['prijava']=1;
        }
        else{
            $validated['prijava']=0;
        }
        return Survey::create($validated);
    }

I need the 'prijava' column to be 1 if checkbox is check or 0 if not. I always get 0 and if I change code in else to for example 2, it will add 2 in column. I also put 'prijava' column to be a boolean.

3 Answers3

0

You don't need to use Input class to check if checkbox is checked or not. Since you already have Request instance, check it like this:

if($request->chk === "1"){
     $validated['prijava']=1;
}
 else{
     $validated['prijava']=0;
 }

Didn't test this, but it should get you desired output. Let me know if you get any errors .

zlatan
  • 3,346
  • 2
  • 17
  • 35
0
$request->has('chk')

will return true if the checkbox is checked, and false if not.

MrEvers
  • 1,040
  • 1
  • 10
  • 18
0

first remove value attribute like this :

<input type="checkbox" name="chk" />

then in your store method update your code to :

public function store(Request $request)
    {
        $validated=$request->validate([
            'title'=>'required',
            'description'=>'nullable'
        ]);
        if($request->has('chk')){
            $validated['prijava']=1;
        }
        else{
            $validated['prijava']=0;
        }
        return Survey::create($validated);
    }

i think this works well

Ahmed Atoui
  • 1,506
  • 1
  • 8
  • 11