How to make Autocomplete search using jQuery UI in Laravel

Autocomplete search enhances website user experience by predicting and completing search queries as the user types. Users can quickly find what they looking for without having to type out their entire query.

jQuery UI has different types of widgets available, and one of them is autocomplete. Data is loaded according to the input after initializing autocomplete on a textbox. User can select an option from the suggestion list.

In this tutorial, I show how you can make autocomplete search using jQuery UI and load its data using AJAX in Laravel 9.

How to make Autocomplete search using jQuery UI in Laravel


Contents

  1. Database Configuration
  2. Table structure
  3. Model
  4. Controller
  5. Route
  6. View
  7. Demo
  8. Conclusion

1. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Table structure

  • Create employees table using migration and add some records.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created.

3. Model

Create Employees Model.

php artisan make:model Employees
  • Specify mass assignable Model attributes – username, name, and email using the $fillable property.

Completed Code

<?php

namespace App\Models;

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

class Employees extends Model
{
    use HasFactory;

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

4. Controller

Create a EmployeesController controller.

php artisan make:controller EmployeesController

Create 2 methods –

  • index() – Load index view.
  • getEmployees() – This method is used to handle AJAX requests.

Assign POST search value to $search. If $search is empty then fetch 5 records from employees table and assign to $employees variable.

NOTE – Remove limit() to fetch all records or update the limit value.

If $search is not empty then fetch records from employees table where $search value exists in name field. Assigned fetched records to $employees.

Loop on the $employees and initialize $response with value and label keys. Pass $employee->id in value key and $employee->name in label key.

Return $response Array in JSON format.

Completed Code

<?php

namespace App\Http\Controllers;

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

class EmployeesController extends Controller
{
   public function index(){

      // Load index view
      return view('index');
   }

   // Fetch records
   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); 
   } 
}

5. Route

  • Open routes/web.php file.
  • Define 2 routes –
    • / – Load index view.
    • /getEmployees – This is used to send AJAX POST request to fetch the employees list for autocomplete.
<?php 
use Illuminate\Support\Facades\Route; 
use App\Http\Controllers\EmployeesController; 

Route::get('/', [EmployeesController::class, 'index']); 
Route::post('/getEmployees', [EmployeesController::class, 'getEmployees'])->name('getEmployees');

6. View

Create a new index.blade.php file in resources/views/ folder.

HTML –

  • Stored CSRF token in the <meta > tag.
  • Include jQuery UI and jQuery libraries.
  • Create 2 text elements –
    • 1st is used to initialize jQuery UI autocomplete.
    • 2nd is used to display the selected option value from the suggestion list.

jQuery –

  • Read csrf_token from meta tag and assign to CSRF_TOKEN variable.
  • Initialize autocomplete on #employee_search element.
  • With source option load suggestion data by sending AJAX request to {{route('getEmployees')}}.
  • Also, pass CSRF_TOKEN along with search value in the data.
  • On successful callback pass response to response() function.
  • Using select option to display selected option label in the #employee_search and value in #employeeid input fields.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <title>How to make Autocomplete search using jQuery UI in Laravel</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" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

</head>
<body>

   <!-- For defining autocomplete -->
   Search User : <input type="text" id='employee_search'> <br><br>

   <!-- For displaying selected option value from autocomplete suggestion -->
   Selected UserID : <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('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>

7. Demo

View Demo


8. Conclusion

You can pass extra data using the data option which you want to use while fetching suggestion data.

View this tutorial, to know jQuery UI autocomplete implementation in Laravel 7.

If you found this tutorial helpful then don't forget to share.