Laravel Blade : Checkbox sends 'null' value to database

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 06:14:59

问题


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>

回答1:


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.

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"

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>

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).

Update

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?

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


来源:https://stackoverflow.com/questions/65712090/laravel-blade-checkbox-sends-null-value-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!