I am trying to show all selected values from database to multiple select2.So when I want to add other events I can add them.
Offer tables:
id:1
title: event1
events: 17,6,8
column events has id of all events selected.
This is what I do:
public function edit($id)
{
$offer=Offers::find($id);
$events=Events::all();
$explode= explode(',', $offer->events);
return view('edit',['offer'=>$offer,'events'=>$events,'explode'=>$explode]);
}
Blade:
<div class="form-group m-form__group row">
<label class="col-xl-3 col-lg-3 col-form-label">****</label>
<div class="col-xl-9 col-lg-9">
<select class="form-control m-select2" id="m_select2_3" name="events[]" multiple="multiple">
<optgroup label="Events">
@foreach($events as $event)
@foreach($explode as $item)
<option value="{{$event->id}}" {{ $item == $event->id ? 'selected="selected"' : ''}}>{{$event->title}}</option>
@endforeach
@endforeach
</optgroup>
</select>
</div>
</div>
So when i select the value it shows three times repeated values

offertoeventsone-to-many relations? You're getting duplicates from yourforeach, there are multipleeventsthatbelongsto anoffer.@foreach $explode, usein_array($event->id,$explode);