Old value in multiple select option in laravel blade

前端 未结 9 1390
感动是毒
感动是毒 2021-02-13 12:08

Here is my select option


                        
    
提交评论

  • 2021-02-13 12:38

    This works fine for me, using collect(old('roles'))->contains($ role)

    Ex:

    <div class="form-group">
      <label for="roles" class="form-control-label">Roles</label>
      <select name="roles[]" id="roles" data-placeholder="Choose role..." multiple class="standardSelect">
        <option value="" label="default"></option>
        @foreach($roles as $role)
          <option value="{{ $role }}" {!! (collect(old('roles'))->contains($role)) ? 'selected="selected"' : '' !!}>{{ $role }}</option>
        @endforeach
      </select>
     </div>
    
    0 讨论(0)
  • 2021-02-13 12:39

    After Playing around a bit I came up with this and it seems to work just splendidly

    <select name="options[]" id="options" class="form-control" multiple>
        @foreach($settings->includes->get('optionList') as $option)
            <option value="{{ $option->id }}" {{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}>{{ $option->name }}</option>
        @endforeach
    </select>
    

    I may be 100% wrong in leveraging the collect function but it works fine on many of my tests. I want to say thank you to MPS as it was your example that really made me try this as when there is no data in "recommended_food" you will pull an error because in_array requires an array and will not work well with null so I then came up with the idea of doing something like this.

    @if (old("options")){{ (in_array($option->id, old("options")) ? "selected":"") }}@endif
    

    inline but man that looks ugly to me so long story short I am using the following instead

    {{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}
    

    Hope this helps others!!

    0 讨论(0)
  • 提交回复
    热议问题