Here is my select option
<select name="recomemded_food[]" value="" style="width:560px;" multiple class="chosen-select" >
<option value="American Black Bear">American Black Bear</option>
<option value="Asiatic Black Bear">Asiatic Black Bear</option>
<option value="Brown Bear">Brown Bear</option>
<option value="Giant Panda">Giant Panda</option>
</select>
And below is my code trying to use the foreach loop to get the array value. but I am receiving the following error:
@foreach (explode(',',old('recomemded_food')) as $recomemded_food)
{{$recomemded_food}}
@endforeach
Error Message : explode() expects parameter 2 to be string
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With