Html Laravel刀片:复选框发送';空';对数据库的价值
我不明白。选中“我的复选框”时,会将“null”值发送回控制器。如果它在DB中,它将返回检查状态,但当我取消选中它,然后再次检查它时,我的表单发送一个“null”值,我做错了什么Html Laravel刀片:复选框发送';空';对数据库的价值,html,laravel,laravel-blade,Html,Laravel,Laravel Blade,我不明白。选中“我的复选框”时,会将“null”值发送回控制器。如果它在DB中,它将返回检查状态,但当我取消选中它,然后再次检查它时,我的表单发送一个“null”值,我做错了什么 <div class="col"> <input type="checkbox" name="staff" @if($child->staff == 'true') checked @endif > </div>
<div class="col">
<input type="checkbox" name="staff" @if($child->staff == 'true') checked @endif >
</div>
staff==“true”)已选中@endif>
checked属性只确定该复选框是否应包含在post
请求中。value
属性确定复选框的值,如果选中该复选框,则该复选框的值将是多少,并因此包含在表单提交中
如果未指定值
,且该复选框包含在post
请求中,则其值将为on
:
<input type="checkbox" name="staff" id="staff">
"staff" => "on"
即使在上述示例中,复选框的值
为真
,如果未选中则不会包含在提交的表单请求中,因此您有一个假
值(技术上)
更新
我希望能够在真与假之间切换。当我将复选框切换为空时,它仍然会将空值传递给DB。有什么想法吗
复选框值是字符串
,因此您需要自己执行到所需值的转换,然后将其存储在数据库中。可以实现的一个例子如下:
public function update(Request $request, Staff $staff)
{
// Perform some validation on the incoming Request
$request->validate([
'staff' => ['in:true,false']
]);
// Assuming we get here, data is valid
// If the Request object has a key named 'staff'
// then the checkbox was checked (true).
// If there is no key named 'staff'
// then the checkbox was not checked (false)
$staff->child = $request->has('staff');
}
你需要提供一个值,目前它没有。那么这是value=“staff”吗?你在表中存储单词“true”
?你是摇滚明星。然而,我希望能够在真与假之间切换。当我将复选框切换为空时,它仍然会将空值传递给DB。有什么想法吗?非常感谢。@Vince如果您从请求中获得空值,那么您可以将checkbox的请求值检查到控制器中,然后将该值传递到数据库$myVar=isset($request->staff==null)?如果你的价值是真的:如果你的价值是假的@文斯一世已经添加了一个例子,说明如何实现你所要求的目标。
public function update(Request $request, Staff $staff)
{
// Perform some validation on the incoming Request
$request->validate([
'staff' => ['in:true,false']
]);
// Assuming we get here, data is valid
// If the Request object has a key named 'staff'
// then the checkbox was checked (true).
// If there is no key named 'staff'
// then the checkbox was not checked (false)
$staff->child = $request->has('staff');
}