Laravel 9 Autocomplete search using jQuery UI

Laravel 9 Autocomplete search using jQuery UI

Laravel 9 Autocomplete search using jQuery UI

In this post, we will give you information about Laravel 9 Autocomplete search using jQuery UI. Here we will give you detail about Laravel 9 Autocomplete search using jQuery UI And how to use it also give you a demo for it if it is necessary.

jQuery UI has different types of widgets available, one of them is autocompleted.

Data is loaded according to the input after initializing autocomplete on a textbox. Users can select an option from the suggestion list.

In this tutorial, I show how you can make autocomplete search using jQuery UI in Laravel 9.

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=employee
DB_USERNAME=root
DB_PASSWORD=

2. Table structure

Create employees table using migration and add some records.

php artisan make:migration employee_table

Now, navigate to database/migrations/ folder from the project root.
Find a PHP file that ends with employee_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 an EmployeeController controller.

php artisan make:controller EmployeeController

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

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

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

HTML –

Stored CSRF token in the 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 8</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>

Conclusion for Laravel 9 Autocomplete search using jQuery UI

Hope this code and post will help you implement Laravel 9 Autocomplete search using jQuery UI. if you need any help or any feedback give it in the comment section or you have a good idea about this post you can give it in the comment section. Your comment will help us to help you more and improve us.

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

59  +    =  64

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US