How to validate if checkbox is checked in laravel?

11,699

Solution 1

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.

Solution 2

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

Share:
11,699
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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
    }