Skip to content
Advertisement

duplicate value on select2 tag on laravel blade template

I found a bug when i try to displayed data on select2 tag. I got duplicate data and I want to know how to fixed it. Im using laravel 7 and here’s my code

This is my controller code:

public function editLocation(Request $request,$id){
$mtFasilitas = DB::table('MT_Facility')->select('id','name')
                                        ->get();
$trFasilitas = DB::table('TR_Fasilitas')->select('idMtFasilitas')
                                         ->where('idDetailLokasi',$id)
                                         ->get();
return view('layout.back.content_kos.edit_kos',['mtFas' => $mtFasilitas, 'trFas' => $trFasilitas]);

}

This is my blade template :

<select class="js-example-basic-multiple form-control mb-4" name="fasilitas[]" multiple="multiple">
                @foreach ($mtFas as $key => $data)
                    @foreach ($trFas as $key2 => $data2)
                        <option value="{{$data->id}}"{{$data2->idMtFasilitas == $data->id ? 'selected="selected"' : ''}}> {{ $data->name}}</option> 
                    @endforeach
                @endforeach
 </select>

And this is the result : enter image description here

Anyone can help me ? Thank you

Advertisement

Answer

$trFasilitas = DB::table('TR_Fasilitas')->select('idMtFasilitas')
                                         ->where('idDetailLokasi',$id)
                                         ->get()
                                         ->pluck('idMtFasilitas')
                                         ->all();
        <select class="js-example-basic-multiple" name="fasilitas[]" multiple="multiple">
            @foreach ($mtFas as $data)
            <option value="{{ $data->id }}" {{in_array($data->id, $trFas) ? 'selected="selected"' : '' : ''}}>
                {{ $data->name }}</option>
            @endforeach
        </select>

I think this should do.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement