Skip to content
Advertisement

how to run to foreach loops for single select tag laravel?

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement