'How to show old data of `select` element in Laravel?

How to show old data of select element in Laravel?

Data can be shown in input like this:

<input id="name" name="name" class="form-control" type="text" value="{{ old('name', $user->name) }}">

when the element is select,how to show the old data?

<select class="form-control" name="gender">
    <option value="male">male</option>
    <option value="female">female</option>
</select>


Solution 1:[1]

Try This:

   <label for="name">Tags</label>
   <select name="tags[]" class="form-control select-tag" multiple>
              @foreach($tags as $tag)
   <option value="{{$tag->id}}" {{in_array($tag->id, old("tags") ?: []) ? "selected": ""}}>{{$tag->name}}</option>
              @endforeach
   </select>

Solution 2:[2]

In my case a ternary operator worked for me.

<select class="form-control" name="gender">
    <option value="male" {{old('gender') == 'male' ? "selected" : ""}}>Male</option>
    <option value="female" {{old('gender') == 'female' ? "selected" : "" }}>Female</option>
</select>

Please be mindful of the double quotes "" around your selected attributes because single quotes will never work.

Solution 3:[3]

this code show old value if validation fail otherwise show value of element

<select class="form-control" name="gender">
    <option value="male" {{old('gender',$user->gender) == 'male' ? 'selected': ''}}>male</option>
    <option value="female" {{old('gender',$user->gender) == 'female' ? 'selected': ''}} >female</option>
</select>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shamsheer
Solution 2 Relcode
Solution 3 e sadeghi