19-04-2022

Laravel Select2 Ajax Autocomplete Example

Sometimes you want to fill your select2 input through api call. With the help of the following examples, you can provide this in a fluent way.

Please keep in mind the followings:

  • - page load will be faster (because select2 input will be empty)
  • - select2 input needs minimum 1 character
  • - after 1 character in the search field, it will look up for the database results
  • - we have a products model with ID and NAME

You can modify the methods, I commented out those block for now.

Let's start!

Add to routes the following line:

Route::get('/select2-autocomplete-ajax', 'SelectTwoAutocompleteController@dataAjax')->name('select-two.item-name');

Make sure to create controller:

php artisan make:controller SelectTwoAutocompleteController

In the controller which you just generated, you will need to define the following method:

// THIS IS THE PROPER REQUEST YOU NEED TO USE
use Illuminate\Http\Request;

/**
  * Show the application dataAjax.
  *
  * @return \Illuminate\Http\Response
*/
public function dataAjax(Request $request)
{
  $data = [];

  if($request->has('q')){
      $search = $request->get('q');
      $data = Product::select('id','name')
      		->where('name','LIKE','%'. $search .'%')
      		->get();
  }
// REMOVE THE COMMENT OF THIS BLOCK SO IT WILL AUTOFILL THE INPUT
// else {
//  $data = Product::select('id','name')
//      		->get();
// }
  return response()->json($data); 
 }

In the view file, you need the following block:

<select class="itemName" name="itemName"></select>

You can see it's "option empty", so just the raw select input, as the select2 documentation shows.

And the following script part:

<script type="text/javascript">
$('.itemName').select2({
  placeholder: 'Select an item',
  minimumInputLength: 1, // COMMENT OUT THIS LINE TO AUTO FILL THE INPUT 
  ajax: {
    url: '{{route('select-two.item-name')}}',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>

Please notice, I used route named parameter to resolve the url.

© 2024 PappZ. All rights reserved.