skip to Main Content

I have a Laravel 9.x project, and when I submit the form and an error occurs, I have managed to keep the already inserted value of the text fields, but I would like the checkboxes to keep their value as well.

<input type="checkbox" name="abono_tasa" value="{{ isset($vado->abono_tasa) ? ($vado->abono_tasa==1 ? 'checked': '') : '' }}" id="abono_tasa">

I would like to control this.

2

Answers


  1. In Laravel, you can keep the old value of a checkbox input when a form is submitted and there are validation errors, using the old function in the Blade templates.

    When you’re rendering the form, you can use the old function to set the checkbox to its previous value if there are validation errors. Here’s an example:

    <input type="checkbox" name="abono_tasa" id="abono_tasa" value="1" @if(old('abono_tasa')) checked @endif />
    

    For convenience, you may use the @checked directive to easily indicate if a given HTML checkbox input is "checked". This directive will echo checked if the provided condition evaluates to true:

    <input type="checkbox" name="abono_tasa" id="abono_tasa" value="1" @checked(old('abono_tasa')) />
    

    Thank you.
    (Please, consider making this answer the selected answer if the solution works for you).

    Login or Signup to reply.
  2. 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="myCheckedValue"
           name="myField"
           @if((!old() && $myDefault) || old('myField') == 'myCheckedValue') checked="checked" @endif />
    

    Always checked by default

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

    Always un-checked by default

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

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

    Related Laracast: https://laracasts.com/discuss/channels/laravel/how-to-set-old-value-for-checkbox-input-using-blade?page=1&replyId=771230

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search