Adam
Adam

Reputation: 507

Select for boolean type in Laravel Blade

I have a flag "active" in mysql database for users, this column is boolean type. From admin account I want to create a select options to select True/False if user is activated or not. So in my form for user's information editing/creating I have:

<div class="form-group{{ $errors->has('active') ? ' has-error' : '' }}">
    <label>Is user active?</label>
    <select class="form-control" name="active" id="active">
        @if (old('active') == $user->active)
            <option value="1" selected>True</option>
        @else
            <option value="0">False</option>
        @endif
    </select>
</div>

The problem is it's only displaying "True" no "false" option if user is activated by PHPMyAdmin parameter changing or "False" option if user i deactivated the same way as above. Please help to understand how to list all options (True/False) and select by default the option previously selected so edit should work.

Upvotes: 1

Views: 8663

Answers (2)

Samundra
Samundra

Reputation: 1909

Try changing your HTML to the following:

<div class="form-group{{ $errors->has('active') ? ' has-error' : '' }}">
    <label>Is user active?</label>
    <select class="form-control" name="active" id="active">
        <option value="1" @if (old('active') == 1) selected @endif>True</option>
        <option value="0" @if (old('active') == 0) selected @endif>False</option>
    </select>
</div>

You should check for the value that was selected before by the user. And then use that value to choose the value. However, in the answer, I am not setting the default value which you should take care of.

Upvotes: 3

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

<div class="form-group{{ $errors->has('active') ? ' has-error' : '' }}">
    <label>Is user active?</label>
    <select class="form-control" name="active" id="active">
            <option value="1" {{ old('active') ? 'selected' }}>True</option>
            <option value="0" {{ !old('active') ? 'selected' }}>False</option>
    </select>
</div>

Upvotes: 2

Related Questions