2

I have a checkbox in my view

<input type="checkbox" id="test5">

and I want to validate in my controller if the checkbox is checked

if (Input::get('test5') === true) {
     //insert 1
} else {
    //insert 0
}

2 Answers 2

6

First, a checkbox (any kind of input must) must have a name and a value.

<input type="checkbox" name="mycheckbox" value="1" id="test6">

Then on your controller you do:

Request::get('mycheckbox')

This will output the value of your checkbox if it's checked, or null if not (browser don't send anything)

if (Request::get('mycheckbox')) {
    // Do anything here
}

Note that the input id attribute don't care. The important here is the input name attribute.

Sign up to request clarification or add additional context in comments.

Comments

1

you can validate everything normally and then when you pass the request to an array with $data = $request->all(); you can check if the checkbox is checked by just checking if the 'mycheckbox' space is empty like:

$dataValidate = $request->validate([
    'something' => 'required|numeric|min:3|max:99',
    'something' => 'required|numeric',
    'something' => 'required|numeric',
    'something' => 'required|alpha_dash',
    'something' => 'required|email',
    'something' => ['required', new SomethingRule],
    'something' => 'required|starts_with:0,+',
    'something' => 'nullable|numeric',
]);
$data = $request->all();
if (empty($data['mycheckbox'])) {
    //something if the checkbox is not checked
}else{
    //something if the checkbox is checked
}

This is something that I do from time to time I dunno if it is the best practice but it does the job and does not make anything worse

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.