Shan Biswas
Shan Biswas

Reputation: 429

Laravel checkbox input old not working properly

I have a form. After submission of the form if it has some error then it redirects to the same page and pre-populate the data that user submitted. I have 3 checkbox fields in that form. Suppose user has checked only the first checkbox and submitted the form. So if the form has some error it will redirect to the same page, but the problem is when it redirects here again then all the checkboxes got selected instead of only the 1st one.

<div class="form-group">
    <label>Hobbies: <span><em>{{$errors->first('hobbies')}}</em></span></label>
    <input type="checkbox" name="hobbies[]" value="Cricket" @if (is_array(old('hobbies'))) && (in_array('Cricket', old('hobbies'))) checked @endif> Cricket
    <input type="checkbox" name="hobbies[]" value="Football" @if (is_array(old('hobbies'))) && (in_array('Football', old('hobbies'))) checked @endif> Football
    <input type="checkbox" name="hobbies[]" value="Badminton" @if (is_array(old('hobbies'))) && (in_array('Badminton', old('hobbies'))) checked @endif> Badminton
</div>

Upvotes: 1

Views: 518

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 14520

You have unbalanced and misplaced parentheses, so your if is not evaluation correctly.

@if (is_array(old('hobbies')) && in_array('Badminton', old('hobbies')))

Upvotes: 1

Rahul
Rahul

Reputation: 18557

You should do this way to make it work,

<div class="form-group">
    <label>Hobbies: <span><em>{{$errors->first('hobbies')}}</em></span></label>
    <input type="checkbox" name="hobbies[]" value="Cricket" {{ !empty(old('hobbies')) && (in_array('Cricket', old('hobbies'))) ? 'checked' : '' }}> Cricket
    <input type="checkbox" name="hobbies[]" value="Cricket" {{ !empty(old('hobbies')) && (in_array('Football', old('hobbies'))) ? 'checked' : '' }}> Football
    <input type="checkbox" name="hobbies[]" value="Cricket" {{ !empty(old('hobbies')) && (in_array('Badminton', old('hobbies'))) ? 'checked' : '' }}> Badminton
</div>

Give it a try, it should work.

Upvotes: 0

Related Questions