Search code examples
laravelsql-updatehtml-selectdropboxdropdown

Laravel dropbox initial value on update


Items belongs to Categories. On edit page for Items I have an html select with Categories. Is this the best solution to have the right initial state for this select?

<select name="id_category" class="form-control">
    @foreach($categories as $category)
        @if($category->id == $item->id_category)
            <option value="{{ $category->id }}">
                {{ $category->name }}
            </option>
        @endif
    @endforeach
    @foreach($categories as $category)
        @if($category->id != $item->id_category)
            <option value="{{ $category->id }}">
                {{ $category->name }}
            </option>
        @endif
    @endforeach
</select>

Solution

  • I'm not sure i understand your question, but i think you want to select item was previously select by user, so you can use inline if to set selected.

    <select name="id_category" class="form-control">
         @foreach($categories as $category)
            <option value="{{ $category->id }}" {{  $category->id == $item->id_category ? "selected" : "" }} >
                {{ $category->name }}
            </option>
         @endforeach
    </select>
    

    Sorry if i didn't understand your question