Márcio Moreira
Márcio Moreira

Reputation: 505

In Laravel how to get old checkbox value during reloads on a edit form in this case?

Situation:

<input type="checkbox" name="commerce" value="1"
    {{ old('commerce', $company->commerce) ? 'checked' : '' }} />
<label>Commerce</label>

The edit form renders with the checkbox checked as expected. After this:

The form reloads because that emptied string field is required. But...

It's easy to undestand that once the checkbox is unchecked, the "commerce" parameter is not passed with the form. So old("commerce") does return anything. Then the default value is used: the value on the database ($company->commerce) that is equal to 1.

In this case, where the value is 1 (true) on the database, how can I make the user option of letting the checkbox unchecked prevail during reloads ?

Thank you, Márcio

Upvotes: 1

Views: 30

Answers (1)

Eyad Bereh
Eyad Bereh

Reputation: 1746

The problem here is that when you don't check a checkbox in your form before submission, then the old() helper doesn't recognize it at all instead of recognizing it as unchecked. So to Laravel it's a null value, and that's why it always sets the state of the checkbox as the value of the $company->commerce field.

A suggested solution would be to add a check whether the value returned by old('commerce') is null or not:

<input type="checkbox" name="commerce" value="1" {{ !is_null(old('commerce')) && old('commerce', $company->commerce) ? "checked" : "" }}/>

Or you can even make it a little bit tidier using the @checked() directive:

<input type="checkbox" name="commerce" value="1" @checked(!is_null(old('commerce')) && old('commerce', $company->commerce))/>

Upvotes: 0

Related Questions