Lugi's avatar
Level 21

How to set old value for checkbox input using Blade ?

Hi there,

I have a single checkbox input named user_agreement. Using Chrome DevTools, I see that the checkbox is clicked - Form Data shows user_agreement: on.

Now I would like to set the checkbox to load old value when appropriate.

How to properly do that ?

I was thinking about this:

@if(old('user_agreement')=='on')) checked @endif

Is that a good way to go ?

0 likes
7 replies
Swaz's avatar
Swaz
Best Answer
Level 20

You're pretty close, you can use shorthand like this:

<label>
    <input 
        type="checkbox" name="agreement" value="on" 
        {{ old('agreement') == 'on' ? 'checked' : '' }}
        >
    I Agree
</label>
9 likes
Lugi's avatar
Level 21

@Swaz Thanks.. Why did you put in value="on" ?

Swaz's avatar

Based on your example, I thought you had "on" as the value of your checkbox. The value can be anything you want, I would typically use "1" in cases like this.

Čamo's avatar

Hi, I am facing this problem right now. But this solution has a problem with default values if checkbox value is in edit form.

anilkumarthakur60's avatar
                            <input class="form-check-input" type="checkbox" name="trend"  value="1" @if (isset($product)) @if ($product->trend==1) checked @endif @endif id="">
1 like
Top-Master's avatar

https://stackoverflow.com/a/71432052/8740349

For variable-based default value

In below, if $myDefault is set to true, it equals checking the check-box by default.

<input type="checkbox" value="myOnValue"
       name="myField"
       @if((!old() && $myDefault) || old('myField') == 'myOnValue') checked="checked" @endif />

Always checked by default

<input type="checkbox" value="on"
       name="myField"
       @if(!old() || old('myField') == 'on') checked="checked" @endif />

Always Unchecked by default

Below does not need "!old()" workaround.

<input type="checkbox" value="on"
       name="myField"
       @if(old('myField') == 'on') checked="checked" @endif />
2 likes

Please or to participate in this conversation.