Autocomplete Search using jQuery UI in Laravel 9

What are autocomplete and predictive search? Autocomplete is a search feature where the search box predicts the user’s query and provides suggestions as the user types. The user can select any of the autocomplete suggestions and be taken to results without having to manually type every character.

In this tutorial, We are going to learn How to create Autocomplete Search using jQuery UI in Laravel 9.

Also Read : How to create Custom Helper in Laravel 9

Autocomplete Search using jQuery UI in Laravel 9

  • Step 1 : Install a fresh Laravel 9 Project
  • Step 2 : Create a Table
  • Step 3 : Create Model
  • Step 4 : Create Route
  • Step 5 : Create Controller
  • Step 6 : Download and Install jQuery UI 
  • Step 7 : Create View
  • Step 8 : Result
  • Step 9 : Conclusion

Step 1 : Install a fresh Laravel 9 Project

First, We are going to install a fresh latest version of Laravel 9. To do so run the following command in the terminal.

Installation Via Composer

composer create-project laravel/laravel laraveltuts

cd laraveltuts

laraveltuts is the project name.

Now, Create the database and enter the details in .env file.

Also Read : How to Create Tabs Using Tailwind CSS and Alpine JS

Step 2 : Create a Table

Now, We are going to create a employees table. Run the following command:

php artisan make:migration create_employees_table

Now open the file navigate to database/migration/ folder from the project root.

There you will find create_employees_table file. Open it and add the following code into the up() function.

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('name');
       $table->string('email');
       $table->timestamps();
    });
}

Save the file and Run the migration.

php artisan migrate

Now the table has been create. Add some records in it. We had entered 10 records.

Step 3 : Create Model

Now we are going to create a model for employees. Create Employees Model by running a following command:

php artisan make:model Employees

Specify mass assignable Model attributes – name, and email using the $fillable property.

app\Models\Employees.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
    use HasFactory;

    protected $fillable = [
        'name','email'
    ];
}

Also Read : Laravel 9 OrderBy ASC and DESC Tutorial

Step 4 : Create Route

Now we are going to create a two route in routes/web.php

Route::get('/','App\Http\Controllers\EmployeesController@index');

Route::post('/employees/getEmployees/','App\Http\Controllers\EmployeesController@getEmployees')->name('employees.getEmployees');

First route is to display view.

Second route is use for ajax request.

Step 5 : Create Controller

Next step is to create Employees Controller. Create EmployeesController Controller using a following command.

php artisan make:controller EmployeesController

Now open the controller which we just create. you can find it in app/Http/Controllers/EmployeesController.php

Import the Employees Model.

Create the two function which we define in route.

  1. index() – Load employees.index view.
  2. getEmployees() – This use to handle AJAX request. Read POST search value and assign in $search.

If $search is empty then select first 5 records from the employees table otherwise use $search in where on the name field and select first 5 records.

Loop on the fetched records. Pass $employee->id in value key and $employee->name in label key.

It will return a $response Array in JSON format.

<?php

namespace App\Http\Controllers;

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

class EmployeesController extends Controller
{
   public function index(){
      return view('employees.index');
   }

   /*
   AJAX request
   */
   public function getEmployees(Request $request){

      $search = $request->search;

      if($search == ''){
         $employees = Employees::orderby('name','asc')->select('id','name')->limit(5)->get();
      }else{
         $employees = Employees::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->limit(5)->get();
      }

      $response = array();
      foreach($employees as $employee){
         $response[] = array("value"=>$employee->id,"label"=>$employee->name);
      }

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

Also Read : How to Install Alpine.js in Laravel 9

Step 6 : Download and Install jQuery UI

Now we are going to download the JQuery UI. Download the latest version of jQuery UI from its website and also download the jQuery library.

Copy download jQuery file in public/ folder.

And we had copied jQuery UI library in public/jqueryui/ folder.

Step 7 : Create View

Now we are going to create a index view file. Create a employees folder at resources/views/

In resources/views/employees/ folder create a new index.blade.php file and add the following code.

<!DOCTYPE html>
<html>
  <head>
    <title>Autocomplete Search using jQuery UI in Laravel 9</title>

    <!-- Meta -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="{{asset('jqueryui/jquery-ui.min.css')}}">

    <!-- Script -->
    <script src="{{asset('jquery-3.6.0.min.js')}}" type="text/javascript"></script>
    <script src="{{asset('jqueryui/jquery-ui.min.js')}}" type="text/javascript"></script>

  </head>
  <body>

    <!-- For defining autocomplete -->
    <input type="text" id='employee_search'>

    <!-- For displaying selected option value from autocomplete suggestion -->
    <input type="text" id='employeeid' readonly>

    <!-- Script -->
    <script type="text/javascript">

    // CSRF Token
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $(document).ready(function(){

      $( "#employee_search" ).autocomplete({
        source: function( request, response ) {
          // Fetch data
          $.ajax({
            url:"{{route('employees.getEmployees')}}",
            type: 'post',
            dataType: "json",
            data: {
               _token: CSRF_TOKEN,
               search: request.term
            },
            success: function( data ) {
               response( data );
            }
          });
        },
        select: function (event, ui) {
           // Set selection
           $('#employee_search').val(ui.item.label); // display the selected text
           $('#employeeid').val(ui.item.value); // save selected id to input
           return false;
        }
      });

    });
    </script>
  </body>
</html>

Step 8 : Result

Autocomplete Search using jQuery UI in Laravel 9

Step 9 : Conclusion

We had use POST method but you can use GET method also for AJAX request.

Initialize jQuery UI autocomplete on an input element and use the source option to send AJAX request for displaying suggestions.

If you found this tutorial helpful and have any feedback or problem please comment below.

Also Read : How to Generate and Read Sitemap XML File in Laravel 9 Tutorial

7 Comments

Leave a Reply