Vince
Vince

Reputation: 1535

Laravel Blade : Checkbox sends 'null' value to database

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>

Upvotes: 2

Views: 2040

Answers (1)

Peppermintology
Peppermintology

Reputation: 10210

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

Upvotes: 3

Related Questions