I just stumbled upon this and I don’t want to repeat such conditions for each form, so I created a function in the Helper class.
helper.php:
class Helper { // other functions public static function oldRadio($name, $value, $default = false) { if(empty($name) || empty($value) || !is_bool($default)) return ''; if(null !== Input::old($name)) { if(Input::old($name) == $value) { return 'checked'; } else { return ''; } } else { if($default) { return 'checked'; } else { return ''; } } // Or, short version: return null !== Input::old($name) ? (Input::old($name) == $value ? 'checked' : '') : ($default ? 'checked' : ''); } }
So now in my forms I just use it like this:
<label>Please select whatever you want</label> <div class="radio-inline"><label><input type="radio" name="whatever" value="1" required {{ Helper::oldRadio('whatever', '1', true) }}> One</label></div> <div class="radio-inline"><label><input type="radio" name="whatever" value="2" {{ Helper::oldRadio('whatever', '2') }}> Two</label></div> <div class="radio-inline"><label><input type="radio" name="whatever" value="3" {{ Helper::oldRadio('whatever', '3') }}> Three</label></div>
Each option passes its name and value to the auxiliary function, and the previously selected one will print 'checked'. In addition, the option can pass "true" as the third parameter, so it is selected if the old input was not.
source share