Pooja
Pooja

Reputation: 613

How to preselect multiple select in laravel 8

I am trying to store multi select value from select option, I am able to save but when I fetch the data from the database, then It is selecting wrong options in select;

category = [{'id' : "1", 'name'=>'A'},{'id' : "2", 'name'=>'B'},{'id' : "3", 'name'=>'C'},{'id' : "4", 'name'=>'D'},{'id' : "5", 'name'=>'E'}]
parent_category = [1,2,3](comming from database)

Blade File :

<select class="js-example-basic-multiple" id="category" name="parent_id[]" multiple>
   <option value=0>None</option>
       @if($categories)
          @foreach($categories as $category)
              <?php $dash=''; ?>
              <option value="{{$category->id}}" @if(in_array($category->id, explode(',',$products->parent_id))) selected @endif>{{$category->name}}</option>
               @if(count($category->subcategory))
                   @include('pages.admin.category.sub-category-list',['subcategories' => $category->subcategory,'products'=>$products])
                 @endif
          @endforeach
       @endif
</select>

sub-category-list.blade.php

<?php $dash.='-- '; ?>
@foreach($subcategories as $subcategory)
    <option value="{{$subcategory->id}} " @if(in_array($subcategory->id, explode(',',$products->parent_id))) selected @endif>{{$dash}}{{$subcategory->name}}</option>
       @if(count($subcategory->subcategory))
          @include('subCategoryList-option',['subcategories' => $subcategory->subcategory,'products'=>$products])
       @endif
@endforeach

As shown in the picture select value is right but data-select-value is wrong

enter image description here

Upvotes: 0

Views: 704

Answers (1)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 330

You can make it as array and make check using in_array function

https://www.php.net/manual/en/function.in-array.php

@if(in_array($category->id, explode(',',$products->parent_id)) selected @endif

As we convert parent_id to array and make a check if id already in it

<select class="js-example-basic-multiple" id="category" name="parent_id[]" multiple>
   <option value=0>None</option>
   @if($categories)
      @foreach($categories as $category)
          <?php $dash=''; ?>
          <option value="{{$category->id}}" @if(in_array($category->id, explode(',',$products->parent_id)) selected @endif>{{$category->name}}</option>
           @if(count($category->subcategory))
               @include('pages.admin.category.sub-category-list',['subcategories' => $category->subcategory])
             @endif
      @endforeach
   @endif

Upvotes: 3

Related Questions