Search code examples
laravel-blade

How to keep select selected with the old() function - laravel blade


i have a search that is driven by a select and i need the option i chose to remain checked when i submit the search, so i used laravel's old() function inside an @if.

<select class="contas_select form-control" name="conta_id" tabindex="1">           
            <option value=" ">&nbsp;</option>
            @foreach($contas as $conta)
                    <option value="{{ old('conta_id') }}" @if( old('conta_id') == request()->conta_id) selected="selected" @endif>
                    {{ $conta->nome }}
                    </option>
            @endforeach
        </select>

but it doesn't work, I don't know why, but it replaces what I selected with the last element inside the option. Does anyone have any suggestions?


Solution

  • You are using old('conta_id') as the value for each option in the select element. This is causing the issue because old('conta_id') will always return the same value for each option within the loop.

    To fix this, you should set the option value to the ID of each $conta, and then check if that ID matches the value of old('conta_id'). Here's how you can adjust your code:

    <select class="contas_select form-control" name="conta_id" tabindex="1">           
        <option value="">&nbsp;</option>
        @foreach($contas as $conta)
            <option value="{{ $conta->id }}" @if(old('conta_id') == $conta->id) selected="selected" @endif>
                {{ $conta->nome }}
            </option>
        @endforeach
    </select>