How to Implement Dynamic AutoComplete Search in Laravel 9 Using Select 2 JS

In this tutorial, we will learn how to implement a dynamic autocomplete search using Select 2 js in Laravel 9. we will explain it step by step with the help of an example.

Step 1: Installing project

Firstly, we will create a new Laravel 9 app and connect it to the local database.

composer create-project laravel/laravel Autocomplete 

Step 2: Creating migration and model 

Now to create migration and model for the students, let’s run the following command in the terminal.

php artisan make:model Student -mf

This command will create a migration, factory, and model for students. let’s navigate these files in their respective directories and write the code.

/database/migrations/2021_05_27_100722_create_students_table.php

<?php

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

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

Now we need to run the migration using the following command:

php artisan migrate

 /Database/Factories/StudentFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class StudentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            

        ];
    }
}

/App/Models/Student.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * Write code on Method
     *
     * @return response()
     */
     protected $fillable = [
        'name', 'email','password',
    ];
}

Step 3: Injecting dummy students

We will inject dummy data using the PHP tinker command.

php artisan tinker
  
Student::factory()->count(20)->create()

Step 4: Creating routs

now we will create two routes, one for indexing the page and the other to process ajax requests for searching in the database asynchronously.

<?php
use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [StudentController::class, 'index']);
Route::get('/studentSearch', [StudentController::class, 'studentSearch'])->name('studentSearch');

Step 4: Create Controller

In this step we will create StudentController using the command below:

php artisan make:controller StudentController

Now in this controller, we will create 2 methods:

  • index()
  • studentSearch()

 app/Http/Controllers/AutocompleteController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class SrudentController extends Controller
{
       /**
        * Write code on Method
        *
        * @return response()
        */
       public function index()
       {
        return view('welcome');
       }

       /**
        * Write code on Method
        *
        * @return response()
        */
       public function studentSearch(Request $request)
       {
            $data = [];

            if ($request->has('q')) {
                $search = $request->q;
                $data = Student::select("id","name")->where('name','LIKE',"%$search%")->get();
            }
            return response()->json($data);
       }
}
Step 5:Create Blade File
In this final step, we will create a welcome.blade.php to the right code for the search frontend.
/resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>Laravel Select2 Dynamic Autocomplete Search - laramatic.com</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>
  <style>
     body{
            padding: 50px;
            background-color: #f7fcff;
        }
  </style>
</head>
<body>
<div class="container mt-4">
  <div class="row">
    <div class="col-md-10 mx-auto">
      <div class="card">
        <div class="card-header bg-success text-white text-center">
          <h4>Laravel Select2 Dynamic Autocomplete Search - laramatic.com</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: '/studentSearch',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>
</html>

Finally, we are ready to run our app and see the results, so run the following command:

php artisan serve

Let’s open the below URL in the browser and see the results.

http://localhost:8000

Output:

Let’s hope this tutorial will give you some insight on how to implement dynamic autocomplete search using Select 2 js in Laravel 9.