Heidel
Heidel

Reputation: 3254

Laravel checkbox always save as 1

There is checkbox in form

{!! Form::checkbox('is_explicit_content', '1', $post->is_explicit_content, ['id' => 'is_explicit_content']); !!} 
{!! Form::label('is_explicit_content', 'Explicit', ['class' => 'checkbox-label']) !!}

model

class Post extends Model
{
    protected $fillable = [
        'text',
        'is_explicit_content'
    ];
}

but value is always saved as 1 and I don't understand why? How to fix it?

Upvotes: 3

Views: 545

Answers (1)

Marwelln
Marwelln

Reputation: 29423

When a checkbox is submitted, it's value is what's given, but if it's unticked, no such form entry is sent.

If you tick the following and submit your form, $_POST['foobar'] is set to 1.

<input type='checkbox' name='foobar' value='1' />

If you leave it unticked, $_POST['foobar'] will be unavailable. If you want to have a default value you need to have a hidden input before your checkbox.

<input type='hidden' name='foobar' value='0' />
<input type='checkbox' name='foobar' value='1' />

Now if you submit the form with foobar unticked, the value of $_POST['foobar'] will be 0.

Upvotes: 7

Related Questions