Old value in multiple select option in laravel blade
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!!
If you pass the select values from Controller:
$recommended_foods = ["American Black Bear",
"Asiatic Black Bear",
"Brown Bear",
"Giant Panda"];
and In the view:
<select required="required" class="form-control" name="recommended_food">
@foreach ($recommended_foods as $key => $food)
<option value="{{ $food}}" {{ (old("recommended_food") == $food ? "selected":"") }}>{{ $food }}</option>
@endforeach
</select>