Laravel can't uncheck checkbox using old with default value set

Viewed 355

I have a very simple checkbox in my application form

<input type="checkbox" name="active" {{ ( empty(old('active')) ? '' : ' checked' ) }}>

My requirements are:

  1. the checkbox should be checked by default when the user arrives on the site for the first time
  2. the checkbox should keep its value after the form validation fails

To me, it seems impossible to achieve this simply by using old as it will either

  • (2) remember the value after validation fails but it will not be checked by default at the beginning
  • (1) be checked by default, e.g. old('active', true) but then it will not be possible to uncheck it (i.e. unchecked box will be checked after validation fails because the default value is set in old).

What is the standard way of dealing with this? Or is there no way around using another field to check if the form was submitted?

<input type="checkbox" name="active" {{ ( empty(old('active')) && !empty(old('submit')) ? '' : ' checked' ) }}>
<input type="hidden" name="submit" value="submit">

Thank you

2 Answers

This maybe dirty but you can append empty string if the $request->active is null.
The code is something like this $request->active ?? '';.

You can pass the default value into old helper.

Try this:

<input type="checkbox" name="active" {{ old('active', true) ? 'checked' : '' }}>
Related