23

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

6
  • old('recomemded_food') is an array in your case. Commented Feb 24, 2016 at 20:05
  • What do you want to achieve ? Commented Feb 24, 2016 at 20:05
  • 2
    Just use the Laravel Collective HTML package, then {!! Form::select('recommnded_food[]', $options, null, ['multiple']) !!}. Commented Feb 24, 2016 at 20:06
  • the select value in view or controller? Commented Feb 24, 2016 at 20:08
  • @JilsonThomas in the view Commented Feb 24, 2016 at 20:09

11 Answers 11

58

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!!

Sign up to request clarification or add additional context in comments.

3 Comments

This should be the accepted answer. Works for Laravel 7.x - I couldn't find a better way online, yet, if any.
Yapp this is better than accepted answer bcz we couldn't put the old value in controller since the old value is come from old request that from view. Work for me too on laravel 7.x
Regarding the in_array variant not working on first page load(i.e; when no options are selected yet on the recommended_food select box, the fix is simple: {{ in_array($food, old("recommended_food")) ?? [] ? 'selected' : '') }}
10

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>

3 Comments

If the user submit the form, may be user forgot to fill up another form and pop up error message. Does the old selected value will be there ?
Yes it will be there.
The question was asked for multiple selection and the answer you gave will work for single selection. Don't know how you got more votes.
9

The question was asked for multiple chosen.

Assuming you have a field called designation and you need to choose multiple designation for adding 1 record and the field name is forWhom

During Add

You need to add this {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }} peace of code to your option tag

which will look like

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
    <option value="">--- Select ---</option>
    @foreach ($desgInfo as $key => $value)
        <option value="{{ $key }}" 
           {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  />
           {{ $value }}
        </option>
    @endforeach
</select>

During Edit

You need to add

{{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }} 

{{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}

which will look like

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
        <option value="">--- Select ---</option>
        @foreach ($desgInfo as $key => $value)
            <option value="{{ $key }}" 
               {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }} 
               {{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}  
               />
               {{ $value }}
            </option>
        @endforeach
    </select>

Select all selected id's in a multiselect dropdown in laravel 5.4 with harvest chosen

Thanks

2 Comments

this worked for me: {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}
This should be the right answer since it is for multiple select.
4

For me Jilson Thomas's answer did not work for multiple select so I changed it to:

{{ in_array($food, old("recommended_food")) ? "selected":"") }}

1 Comment

This does not work on first page load(i.e; when no options are selected yet on the recommended_food select box. This works: {{ in_array($food, old("recommended_food")) ?? [] ? 'selected' : '') }}
3

I think the best answer to this question is this below

@if(count($categories) > 0)
  @foreach($categories as $category)
      <option value="{{ $category->id }}" {{ (old('lawyer_fields') == null ? '' : in_array($category->id ,old('lawyer_fields')) ? "selected":"") }}>
                                            {{ $category->name }}
      </option>
  @endforeach
  @else
       <option disabled>بدون انتخاب</option>
@endif

Comments

3

Best way:

<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>

Comments

1

This is the way I do, very dynamic.

<select id="gender" name="gender">
    <option>Select</option>
        <option value="M">Male</option>
        <option value="F">Female</option>
</select>

<script>
    var currentGender = null;
    for(var i=0; i!=document.querySelector("#gender").querySelectorAll("option").length; i++)
    {
        currentGender = document.querySelector("#gender").querySelectorAll("option")[i];
        if(currentGender.getAttribute("value") == "{{ old("gender") }}")
        {
            currentGender.setAttribute("selected","selected");
        }
    }
</script>

Comments

1

For edit form where on first view you will need to show previous selected options from database

<select name="roles[]" multiple="multiple">
    @foreach($rolesas $key => $value)
        <option value="{{ $key }}"
            @selected(in_array($key, old('roles', $selectedRoles ?? [])))
                >{{ $value }}</option>
    @endforeach
</select>

Comments

0

I was parsing JSON data, and was faced with repopulating the multi-select as an array, and only wanted one table, and wasn't using keys since this array was being passed back from the show method in the controller, so had to supply the values directly on the template, in my case as a crud resource on the edit.blade.php template (also on the create template).

This worked for me, and was the cleanest I could get it on the view.

<select id="recommended_food"   multiple="multiple" size=3 style='height: 100%;' name="recommended_food[]">
    @if ($food->recomemded_food)
      {{ ($val = 'Fries')
        && $chosen = in_array($val, $food->recommended_food)
        ? 'selected':null}}
      <option value="{{$val}}" {{$chosen}}>{{$val}}</option>
      {{ ($val = 'Hot Dogs')
        && $chosen = in_array($val, $food->recommended_food)
        ? 'selected':null}}
      <option value="{{$val}}" {{$chosen}}>{{$val}}</option>
      {{ ($val = 'Hamburgers')
        && $chosen = in_array($val, $food->recommended_food)
        ? 'selected':null}}
      <option value="{{$val}}" {{$chosen}}>{{$val}}</option>
    @endif
  </select>

Comments

0

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>

Comments

0

According to laravel 9 Documentation

You can now use @selected directive like so:

  <select name="version">
    @foreach ($product->versions as $version)
        <option value="{{ $version }}" @selected(old('version') == $version)>
            {{ $version }}
        </option>
    @endforeach
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.