1

I want to retrieve data using Laravel Collective Select with Select2 from a controller using this code:

public function create() {
   $customers=Customer::all();
   $customerAlt= Customer::get()->pluck('customer_name', 'id')->prepend('Please Select', '');
   return view('req.create', compact 'customer', 'customerAlt')
}

now on my blade view, I want to use Laravel collective something like this if using a normal form

<select id="NamaPelanggan" name="nama_pelanggan" class="form-control"> 
 <option>Pilih Satu</option>
    @foreach($customers as $cus)
     <option data-contact="{{ $cus->contact_person }}" data-phone="{{ $cus->phone_number }}" value="{{$cus->id}}">{{$cus->name}}</option>
    @endforeach
</select>

And The JS is below to fill other text field PIC and PIC_Phone

     $('#NamaPelanggan').change(function() {
          let contact = $(this).find(':selected').data('contact_person');
          let phone = $(this).find(':selected').data('phone_number');
          $('#PIC').val(contact);
          $('#PIC_Phone').val(phone);
      })

The Question is how I use laravelcollective with select2 to replace the normal select above and which $customer that I should use

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64

1 Answers1

0

Replace your select element with laravelcollective equivalent, and pass select2 css class as attribute, like this:

{!! Form::select('customer', $customers, null, ['class' => 'select2']) !!}

Customer must be a 2 dimensional array, with key => value, where key will be html option value, and value will be html option label.

$customers = [
    1 => 'Customer A',
    2 => 'Customer B',
]

---EDITED---

To add extra attributes to options fields, like data-contact and data-phone, you can pass it as an array as fifth parameter.

Pay attention to this: the fifth parameter is an array with attributes to options elements; the fourth parameter is and array with attributes to select element.

LaravelCollective select element allow you to pass this fifth parameter as an array indexed by your select values, and in each index you must have another array with your extra attributes. So you will need 02 arrays to achieve what you need.

  1. first array $customers to pass as value and label;
  2. second array $extraParameters to pass, where each index is a value of previous array.

Suppose this is your first array:

$customers = [
    1 => 'Customer A',
    2 => 'Customer B',
]

This should be your second

$extraParameters = [
    1 => ['data-contact' => 'Customer A Contact', 'data-phone' => 'Customer A Phone'],
    2 => ['data-contact' => 'Customer B Contact', 'data-phone' => 'Customer B Phone']
]
{!! Form::select('customer', $customers, null, ['class' => 'select2'], $extraParameters) !!}
Luis de Brito
  • 692
  • 4
  • 7