Skip to content
Advertisement

Laravel select tags in edit page

I cannot get assigned tags in my view as auto selected:

Logic

  1. Get all tags $tags.
  2. Get assigned tags from database $tags2.
  3. Auto select assigned tags.

Code

<select class="chosen-select-tags" name="tags[]" multiple id="tags">
  @foreach ($tags as $tag)
    <option value="{{$tag->id}}"
      // selecting old tags
      @foreach($tags2 as $tt)
       {{ $tag->id == $tt ? 'selected' : '' }}
      @endforeach
      // end of selecting old tags
    >{{$tag->title}}</option>
  @endforeach
</select>

Values

$tags array of assigned tags to my model in this case 2, result

array:2 [▼
  0 => "40b7ea5f-a2d8-4b4e-af6c-b023c2b75db3"
  1 => "533c66f6-073b-4342-8fb1-ec5ede3a0c9c"
]

this two uuid should be auto selected in $tags which is is my full tags array.

Current result

one

Nothing has been selected.

Note: I am using chosen for my select input

Advertisement

Answer

try in_array()

ref link https://www.w3schools.com/php/func_array_in_array.asp

<select class="chosen-select-tags" name="tags[]" multiple id="tags">
    @foreach ($tags as $tag)
    <option value="{{$tag->id}}" {{ in_array($tag->id,$tag2) ? 'selected' : '' }}>{{$tag->title}}</option>
    @endforeach
</select>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement