autocomplete ajax search in laravel 9 using jquery ui

Autocomplete Ajax Search in Laravel 9 Using JQuery UI With Examples

In this tutorial, we will learn about the implementation of autocomplete Ajax search using JQuery UI with an example in Laravel 9. In this autocomplete search we will add search text into the search box and it asynchronously fetches the search results from the database and display it in search suggestions.

Step 1: Install Laravel 9

In this first step, we will install the laravel Application with the name “AutocompeleteSearch”.

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

Step 2: Creating migration, factory, and model 

Now to create a migration, factory, 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 as, a factory and a model for students. here we are generating a factory that will help us inject dummy student’s data into the database which we will do in step 3. 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('/autoCompeleteSearch', [StudentController::class, 'autoCompeleteSearch'])->name('autoCompeleteSearch');

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\User;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
      
        return view('welcome');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autoCompleteSearch(Request $request)
    {


        $searchData = User::select("name as value", "id")
        ->where('name', 'LIKE', '%'. $request->get('search'). '%')
        ->get();

        return response()->json($searchData);
    }
}

 

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 9 jQuery UI autocomplete ajax search - Laramatic.com</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    </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 9 jQuery UI autocomplete ajax search - Laramatic.com</h4>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-12">
                    <input class="itemName form-control" id="search" type="text">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>



<script type="text/javascript">
    var path = "{{ route('autoCompleteSearch') }}";

    $( "#search" ).autoCompleteSearch({
        source: function( request, response ) {
          $.ajax({
            url: path,
            type: 'GET',
            dataType: "json",
            data: {
               search: request.term
            },
            success: function( data ) {
               response( data );
            }
          });
        },
        select: function (event, ui) {
           $('#search').val(ui.item.label);
           return false;
        }
      });

</script>

</body>
</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:

Screenshot 1

I hope this example help you to learn about how to implement autocomplete search usoig JQuery UI in Laravel 9.