laravel 如何验证是否在laravel中选中了复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40732200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:47:34  来源:igfitidea点击:

How to validate if checkbox is checked in laravel?

phphtmllaravellaravel-4

提问by lilly

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
}

回答by Elias Soares

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 nullif not (browser don't send anything)

如果选中或未选中,这将输出复选框的值null(浏览器不发送任何内容)

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

Notethat the input idattribute don't care. The important here is the input nameattribute.

请注意,输入id属性并不关心。这里重要的是输入name属性。

回答by Antonio

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:

您可以正常验证所有内容,然后当您将请求传递给数组时,$data = $request->all();您可以通过检查“mycheckbox”空间是否为空来检查是否选中了复选框:

$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

这是我不时做的事情,我不知道这是否是最佳实践,但它可以完成工作并且不会使任何事情变得更糟