Home > Back-end >  how to run to foreach loops for single select tag laravel?
how to run to foreach loops for single select tag laravel?

Time:09-16

I want to show previously selected options as selected, I have two data sets.

  1. blocks that are JSON encoded in a column with country codes.
  2. countries list from the country table

I want to compare both and want to show countries selected that are present in users blocked colmn JSON encoded

 $user = User::find(auth()->user()->id);
    $blocks = json_decode($user->blocked);
    @foreach(  Countries::orderBy('country_name')->get() as $country )
     <option  value="{{$country->country_code}}"  >{{ $country->country_name }}</option>
    @endforeach

i tried following but it selects on 1 value either 1st or last

 @foreach ($sundaysArray as $key => $value)

               
 @foreach(  Countries::orderBy('country_name')->get() as $country )
                    
<option @if( $value == $country->country_code ) selected="selected" @endif value="{{$country->country_code}}"  >{{ $country->country_name }}</option>
                        @endforeach
                      @endforeach

CodePudding user response:

Thanks to @gert-b

$user = User::find(auth()->user()->id);
$sundaysArray = json_decode($user->blocked);
@foreach(  Countries::orderBy('country_name')->get() as $country )
<option @if (in_array($country->country_code,$sundaysArray)) selected="selected" @endif value="{{$country->country_code}}"  >{{ $country->country_name }}</option>
@endforeach

CodePudding user response:

$selected = explode(",", $products->supplier_id);

<select  name="supplier_id[]" multiple="multiple">
   @foreach($suppliers as $supplier)
     <option value="{{ $supplier->id }}" {{ (in_array($supplier->id, $selected)) ? 'selected' : '' }}>{{ $supplier->name}}</option>
   @endforeach
</select>
  • Related