Wutame
Wutame

Reputation: 69

Laravel: How to save checkbox value

I get this error, when I submit the form

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'onloan' cannot be null

Please help. Sorry for the noob question. I've been searching but the examples are different.

edit.blade.php

<div class="form-group">
  <input type="checkbox" class="" id="onloan" value="1" {{ $item->onloan == 1 ? 'checked' : '' }}>
  <label for="onloan">On Loan</label>
</div>

controller

    public function update(Request $request, Item $item)
    {
        $item->update([
            'name' => $request->name,
            'description' => $request->description,
            'barcode' => $request->barcode,
            'onloan' => $request->onloan //Not Working
        ]);
    }

Upvotes: 5

Views: 2821

Answers (1)

STA
STA

Reputation: 34668

add name="onloan" on your input field, otherwise it won't pass data with form submit method.

<input type="checkbox"  class="" name="onloan" id="onloan" value="1" {{ $item->onloan == 1 ? 'checked' : '' }}>

If you uncheck the checkbox, then it will send nothing with submit, so from your controller you can give a value (0) if value is not passed :

'onloan' => ($request->onloan) ? '1' : '0';

Or,

if(isset($request->onloan)) {
  $onloan = "1";
} else {
  $onloan = "0";
}

'onloan' => $onloan,

Upvotes: 3

Related Questions