Reputation: 2462
I have a select box in my update form with different payment type. I need to select multiple data. If user already have payment type in table then fetch the data and load in selectbox. I have added these feature but in dropdown multiple times data is showing. Please find the image I have attached.
Actually user have three payment type. The dropdown shows these payment type in three times.
Please check the code given below and correct me.
$cabin->payment_type = payment type from user table
$cabinInfo->paymentType() = Generating array in controller
update.blade.php
@inject('cabinInfo', 'App\Http\Controllers\Cabinowner\DetailsController')
<select id="payment" name="payment" class="form-control payment" multiple="multiple" data-placeholder="Choose payment type" style="width: 100%;">
@foreach($cabin->payment_type as $payment)
@foreach($cabinInfo->paymentType() as $paymentTypeKey => $paymentType)
<option value="{{ $paymentTypeKey }}" @if($paymentTypeKey == $payment || old('payment') == $payment) selected="selected" @endif>{{ $paymentType }}</option>
@endforeach
@endforeach
</select>
script
/* Multiple select for payment */
$(".payment").select2();
UpdateController.php
public function index()
{
$cabin = Cabin::where('id', Auth::user()->id)
->first();
return view('update', ['cabin' => $cabin]);
}
public function paymentType()
{
$array = array(
'0' => "Cash",
'1' => "Debit Card",
'2' => "Credit Card",
);
return $array;
}
Upvotes: 0
Views: 1053
Reputation: 673
I am assuming that $cabin->payment_type
returns an array? If so Your logic should more like this:
@inject('cabinInfo', 'App\Http\Controllers\Cabinowner\DetailsController')
<select id="payment" name="payment" class="form-control payment" multiple="multiple" data-placeholder="Choose payment type" style="width: 100%;">
@foreach($cabinInfo->paymentType() as $paymentTypeKey => $paymentType)
<option value="{{ $paymentTypeKey }}" @if(in_array($paymentTypeKey, $cabin->payment_type )|| in_array(old('payment'), $cabin->payment_type )) selected="selected" @endif>{{ $paymentType }}</option>
@endforeach
</select>
Upvotes: 1