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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x