Laravel Blade:复选框将'null'值发送到数据库 [英] Laravel Blade : Checkbox sends 'null' value to database

查看:60
本文介绍了Laravel Blade:复选框将'null'值发送到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白.选中时,我的复选框"会将空"值发送回我的控制器.如果它在数据库中,它将再次检查,但是当我取消选中它,然后再次检查它时,我的表单将发送一个空"值,我在做什么错了?

I don't get it. My Checkbox sends a 'null' value back to my controller when checked. If it is in the DB it will come back checked, but the moment I uncheck it, and then check it again, my form sends a 'null' value What am I doing wrong?

<div class="col">
  <input type="checkbox" name="staff"   @if($child->staff == 'true') checked @endif >
</div>

推荐答案

checked 属性只是确定该复选框是否应包含在 post 请求中. value 属性确定如果复选框被选中并因此包含在表单提交中,则复选框的值将是什么.

The checked attribute just determines whether or not the checkbox should be included in the post request. The value attribute determines what the value of the checkbox will be if it is checked and therefore included in the form submission.

如果您未指定 value ,并且该复选框包含在 post 请求中,则其值将为 on :

If you do not specify a value and the checkbox is included in the post request, its value will be on:

<input type="checkbox" name="staff" id="staff">

"staff" => "on"

如果要使用 true 值,则需要进行设置.

If you want a true value, you'll need to set it.

<input type="checkbox" name="staff" value="true"
    @if($child->staff == 'true') checked @endif>

即使在上面的示例中,复选框的 value true ,如果未进行选中,则不会将其包含在提交的表单请求,因此您(技术上)拥有一个 false 值.

Even though in the above example the value of the checkbox is true, if it is not checked it will not be included in the submitted form request and so you have a false value (technically).

更新

我希望能够在true和false之间切换.当我将复选框切换为空时,它仍将null传递给数据库.有什么想法吗?

I want to be able to toggle between true and false. When I toggle the checkbox to empty it still passes a null to the DB. Any ideas?

复选框的值是 strings ,因此您需要自己转换为所需的值,然后将其存储在数据库中.可以实现的示例如下:

Checkbox values are strings so you will need to perform a conversion to the desired value yourself and then store that in the database. An example of this could be achieved is below:

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');
}

这篇关于Laravel Blade:复选框将'null'值发送到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆