K3nzie
K3nzie

Reputation: 465

Laravel Blade Form Multiselect selected using array not working

I'm trying to get a multiselect in a form to work, I'm using laravel and I pass to my view a variable called correlated, an array of IDs, referring to the models related to select's model, here's the code where I make the confrontation :

@foreach($categories as $category)

                @foreach($correlated as $c)
                @if($c === $brand_id)
                @php($selected = "selected")
                @endif
                @endforeach
                <option class="text-center" value="{{ $category->id }}" selected="{{ $selected }}">{{ ucfirst($category->name) }}</option>
              @endforeach

I checked both brand_id and $c values, they're correct. Any ideas?


edit : corrected, seems the most correct, way, still not working...

@php $selected = "" @endphp
            <select multiple name="categoriesField[]" class="form-control" size="{{ count($categories) }}">
              @foreach($categories as $category)
              @php $selected = '' @endphp
              @if(in_array($category->id, $correlated))
              @php $selected = 'selected' @endphp
              @endif            
                <option class="text-center" value="{{ $category->id }}" @php echo $selected @endphp>{{ ucfirst($category->name) }}</option>
              @endforeach
            </select>

edit 2: solved with code above, my browser somehow behaved wrong and didn't diplay the selected option, guess I'll check the only answer.

Upvotes: 1

Views: 1912

Answers (1)

Vikash
Vikash

Reputation: 3551

You can try this

Before your <select> tag store the brand ids in a variable

@php $brandIds = collect($correlated)->toArray() @endphp

Inside your <select> tag check if the value of your $brand_id variable is inside the $brandIds array using php in_arrya() function, then select that option as selected.

@foreach($categories as $category)
   <option class="text-center" value="{{ $category->id }}" @if(in_array($brand_id, $brandIds)) selected @endif>{{ ucfirst($category->name) }}</option>
@endforeach

Hope this will work for you :)

Upvotes: 1

Related Questions