我对
laravel
有点陌生,我正在开发一个 laravel
应用程序,该应用程序有一个 checkbox
字段,当用户检查 boolean
时,该字段的 1
值应为 checkbox
,当 0
未选中时,checkbox
。
我想检索布尔值 1 或 0 并保存在数据库中。
请帮忙?
查看
<form method="POST" action="{{ route('b2c.getplans') }}" id="travel_form" accept-charset="UTF-8">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="check-now {{ $errors->has('spouse') ? ' has-error' : '' }}">
<h1 class="cover-travel">I am travelling with</h1>
<label class="spouse-me">
<h1 class="pumba">Spouse</h1>
<input id="spouse" type="checkbox" name="spouse">
<span class="checkmark" name="spouse"></span>
</label>
@if ($errors->has('spouse'))
<span class="help-block">
<strong>{{ $errors->first('spouse') }}</strong>
</span>
@endif
</div>
<button type="submit" class="form-b3c"> Get Plans</button>
</form>
控制器
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'WithSpouse' => (\Input::has('spouse')) ? 1 : 0;
]
}
第一种方法是从前端发送正确的值
您可以在前端添加 jquery 或 javascript 在复选框的更改事件上:
<input type="checkbox" name="checkbox" id="myCheckbox" />
<script>
$(document).on('change','#myCheckbox',function(){
if($(this).is(':checked')){
$('#myCheckbox').val(1);
}else{
$('#myCheckbox').val(0);
}
});
</script>
在您的后端,现在您可以检查:
$yourVariable=$request->input('checkbox');
第二种方法只是在你的后端检查
如果选中,您将获得
checkbox value=on
if($request->input('checkbox')=='on'){
$yourVariable=1;
}else{
$yourVariable=0;
}
您也可以使用三元条件,例如:
$yourVariable = $request->input('checkbox')=='on' ? 1:0;
您不必验证复选框值。因为如果它是
checked
,它会发送 on
的值,如果不是 checked
,它不会发送任何内容。
所以,您所需要的只是获取复选框是否被选中,您可以按照以下方式进行。
检索复选框的布尔值,
控制器
// since you haven't provide any codes in the controller what
// are you gonna do with this value,
// I will juts catch it to a variable.
$isChecked = $request->spouse == 'on'
对于那些使用 FormRequest 且无法使接受的答案起作用的人,请将 this 放入prepareForValidation 函数 :
$this->merge(['checkbox' => $this->has('checkbox')]);
简而言之,这将检查请求是否具有复选框值(如果收到,则为“on”,如果未选中复选框则为空),并在验证之前替换请求中的值。
在控制器内部,它也可以作为布尔值使用!
从请求中检索复选框值作为布尔值:
$yourModel->with_spouse = (bool) $request->spouse;
如果选中复选框,则其值(默认为
on
)将传递给请求,并将非空字符串转换为布尔值将为您提供true
。如果未选中复选框,则 spouse
键根本不会传递给请求,因此 $request->spouse
将返回 null
。将 null
转换为布尔值将得到 false
(在 PHP 中,true
是 int 1
,false
是 int 0
,这正是您想要的)。