Search code examples
laravelforeachhtml-selectselectedlaravel-8

Laravel select old and new value as selected


Not sure exactly how to ask this question. But how do you select the old value after you fetched the value from the database? When you click on edit, you fetch the database result. But if something goes wrong, I want the value selected that the user inserted.

This is what works if you want to add a value.

<select name="category_id" class="form-control" id="category">
    @foreach($category as $cat)
        <option value="{{$cat->id}}"
            {{ old('category_id', $cat->id) == $subCategory->category_id ? "selected" : "" }}>
            {{ $cat->category_en }} | {{ $cat->category_de }}</option>
    @endforeach
</select>

However, when I press update, it doesn't use the old selected value, but it automatically goes to the first option in the foreach.


Solution

  • use optional() helper along with the old() helper to handle this kind of situation.

    <option value="{{ $cat->id }}" @if (old('category_id', optional($subCategory)->category_id) == $cat->id) selected @endif>{{ $cat->category_en }} | {{ $cat->category_de }}</option>
    

    what this means is when it gets old input value null, it will use the object value to select an item. when there is old input value it will select the old input value. you can omit the optional helper though, it is useful when you are using the same form for create and update.