Hello Devs,

In this tutorial, we are going to learn about how to create auto complete using Select2 and Ajax in laravel.

Follow this step by step guide given below:



Step 1 : 

Install Laravel 7 Application

composer create-project --prefer-dist laravel/laravel blog


Database Configuration  .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret



Step 2: 

Create product Table and Model

php artisan make:model Product -m

/database/migrations/2020_03_05_100722_create_product_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}


Run this command:

php artisan migrate


/app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected $fillable = [
        'name', 'price',
    ];
}



Step 3: 

Create Route

/routes/web.php

Route::get('select2', 'Select2AutocompleteController@index');
Route::get('/select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');



Step 4: 

Create Controller

php artisan make:controller Select2AutocompleteController


/app/Http/Controllers/Select2AutocompleteController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;

class Select2AutocompleteController extends Controller
{
    /**
    * Show the application layout.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
    	return view('select2.index');
    }
    /**
    * Show the application dataAjax.
    *
    * @return \Illuminate\Http\Response
    */
    public function dataAjax(Request $request)
    {
    	$data = [];

        if($request->has('q')){
            $search = $request->q;
            $data =Product::select("id","name")
            		->where('name','LIKE',"%$search%")
            		->get();
        }
        return response()->json($data);
    }
}



Step 5:

Create View

/resources/views/select2/index.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel - Dynamic autocomplete search using select2 JS Ajax-rathorji.in</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body class="bg-dark">
<div class="container mt-4">
  <div class="row">
    <div class="col-md-8 offset-md-2">
      <div class="card">
        <div class="card-header">
          <h4>Laravel - Dynamic autocomplete search using select2 JS Ajax</h4>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-12">
              <select class="itemName form-control" name="itemName"></select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script type="text/javascript">
$('.itemName').select2({
  placeholder: 'Select an item',
  ajax: {
    url: '/select2-autocomplete-ajax',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>
</html>


Run this command:

php artisan serve


Open this URL:

http://localhost:8000/select2


I hope this example helps you.