Laravel 9 Select2 Dynamic Autocomplete Search Example

May 06, 2022 . Admin

Hey Artisan,

Today, I will explain you how to select2 dynamic autocomplete search using laravel 9.I will create auto complete using Select2 and Ajax in laravel 9. we will show auto complete using select2.js in laravel 9. you can easily create auto complete using select2 and ajax in laravel 9.

I will give you full example of select2 ajax in laravel 9 you can check that code and follow my all step.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

In this step, we need to make database configuration, you have to add following details on your .env file.

  • Database Username
  • Database Password
  • Database name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

.env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create students Table and Model

In second step we have to engender migration for students table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:model Student -m

After this command you have to put bellow code in your migration file for engender students table.

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 require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create students table.

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: Create Route

now, we require to integrate resource route for select2 crud operations in laravel 9 application. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use App\Http\Controllers\AutocompleteController;
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('select2', [AutocompleteController::class, 'index'])->name('select2');
Route::get('/select2-autocomplete', [AutocompleteController::class, 'ajaxdata'])->name('select2-autocomplete');
Step 4: Create Controller

Now,in this step we should create new controller as AutocompleteController. So run bellow command and create new controller.

php artisan make:controller AutocompleteController

Now ,in this controller engender two method :

  • index()
  • ajaxdata()

So, let's copy bellow code and put on AutocompleteController.php file.

app/Http/Controllers/AutocompleteController.php
<?php

namespace App\Http\Controllers;

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

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

       /**
        * Write code on Method
        *
        * @return response()
        */
       public function ajaxdata(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 the last step we have to engender index.blade.php files. So finally you have to create following bellow blade file:

here create following file and put bellow code.

resources/views/index.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 - Dynamic autocomplete search using select2 JS Ajax</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-dark text-white text-center">
                        <h4>Laravel 9 Select2 Dynamic Autocomplete Search - Mywebtuts.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>
    <script type="text/javascript">
        $('.itemName').select2({
            placeholder: 'Select an item',
            ajax: {
                url: '/select2-autocomplete',
                dataType: 'json',
                delay: 250,
                processResults: function (data) {
                    return {
                        results:  $.map(data, function (item) {
                            return {
                                text: item.name,
                                id: item.id
                            }
                        })
                    };
                },
                cache: true
            }
        });
    </script>
</body>
</html>
Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/select2

Output:

It will help you....

#Laravel 9