Search code examples
laravelcheckboxlaravel-5.3

How should I work with checkbox in laravel?


In my create.blade.php I have the following code:

<div class="form-check">
        <label for="active">active</label>
        <input id="active" name = "active" type="checkbox" class="form-check-input" value="1">
    </div>

And in my edit.blade.php the following:

<div class="form-check">
            <label for="active">active</label>
            <input id="active" name = "active" type="checkbox" class="form-check-input" value="{!!$company->
            active!!}"> 
        </div>

SQLFiddle of my db structure with data.

  1. When submitting either with the checkbox checked they work fine
  2. When editing a record with active set to 1, the checkbox isn't checked when opening the form

I know there's no value when not checked and when opening the checkbox isn't 'on' because the value is 1 instead of 'on'.

How can I resolve this problem?


Solution

  • It's actually an HTML problem, you are just using the input the wrong way, you have to use the checked instead of value:

    <input 
       id="active" 
       name="active" 
       type="checkbox" 
       class="form-check-input" 
       checked="{{ $company->active ? 'checked' : '' }}"
    >