How to Add jQuery UI autocomplete in Livewire – Laravel

Autocomplete widget in the jQuery UI library displays an items list that matches with the search value in the textbox.

You can either predefine its data or load it dynamically.

In this tutorial, I show how you can add jQuery UI autocomplete in the Livewire component in your Laravel 9 project.

How to Add jQuery UI autocomplete in Livewire - Laravel


Contents

  1. Add Database configuration
  2. Create a Table
  3. Create Model
  4. Create Controller
  5. Create Route
  6. Create Livewire Component
  7. Create View
  8. Output
  9. Conclusion

1. Add Database configuration

Open .env file to update the database connection.

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. Create a Table

  • Create a table employees using migration.
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('emp_name',60);
       $table->string('email',80);
       $table->string('city',100);
       $table->smallInteger('status');
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and I added some records to it.

3. Create Model

  • Create Employees Model –
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – emp_name, email, city, and status 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 = [ 
        'emp_name','email','city','status'
    ];
}

4. Create Controller

  • Create PagesController controller.
php artisan make:controller PagesController
  • Open app\Http\Controllers\PagesController.php file.
  • Create 1 method –
    • index() – Load index view.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function index(){
        return view('index');
    }
}

5. Create Route

  • Open routes/web.php file.
  • Define 1 route –
    • / – Load index view.
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PagesController;

Route::get('/', [PagesController::class, 'index']);

6. Create Livewire Component

  • Create jqueryui-autocomplete component –
php artisan make:livewire jqueryui-autocomplete

This will create 2 files –

  • app/Http/Livewire/JqueryuiAutocomplete.php
  • resources/views/livewire/jqueryui-autocomplete.blade.php

app/Http/Livewire/JqueryuiAutocomplete.php

  • Include App\Models\Employees model.
  • Create 2 property variables –
    • $searchEmployee – Store selected employee name from the suggestion list.
    • $selEmployeeId – Store selected employee id from the suggestion list.
  • Create 1 method –
    • getData() – This method calls when a search value typed in the autocomplete element. If $search is empty then fetch 5 records from the employees table otherwise, fetch 5 records from the employees table where $search is matched in the emp_name field.

Loop on the fetched records. Initialize $response Array with value and label keys. Pass employee id in value key and name in label key.

Return $response Array in JSON format.

Completed Code

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Employees;

class JqueryuiAutocomplete extends Component
{
     public $searchEmployee = "";
     public $selEmployeeId = 0;

     // Fetch autocomplete Data
     public function getData($search = ""){

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

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

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

     public function render()
     {
          return view('livewire.jqueryui-autocomplete');
     }
}

resources/views/livewire/jqueryui-autocomplete.blade.php

  • Create 2 textboxes –
    • First textbox is use to initialize jQuery UI autocomplete. Add autocomplete class and wire:model="searchEmployee".
    • Second textbox is use to display the selected item id. Here, also add model – selEmployeeId.

Script –

  • Initialize Autocomplete on autocomplete class.
  • Here, add 2 options –
    • source – Call component getData() method using @this.getData(). In the method pass the search value.

It will return JSON data with Promise. For reading it use then. JSON.parse the data and pass it in response().

    • select – Using this option read selected item value and label. With @this.set update model values. Store ui.item.label in searchEmployee and ui.item.value in selEmployeeId.

Completed Code

<div>

     <input type="text" class='autocomplete' wire:model="searchEmployee"> <br><br>
     <br>
     <input type="text" wire:model="selEmployeeId">
</div>

@section('scripts')

<!-- Script -->
<script >
$(document).ready(function(){

     $( ".autocomplete" ).autocomplete({
          source: function( request, response ) {

               var responseData = @this.getData(request.term);

               responseData.then((data) => {
                    var data = JSON.parse(data);
                    response( data );
               });

          },
          select: function (event, ui) {

               @this.set('searchEmployee', ui.item.label);
               @this.set('selEmployeeId', ui.item.value);

               return false;
          }
     });

});

</script>

@endsection

7. Create View

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

Include jQuery and jQuery UI library –

<!-- jQuery UI CSS -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

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

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

Include jqueryui-autocomplete component, livewire style, and script. Also, add @yield('scripts').

Completed Code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Add jQuery UI autocomplete in Livewire - Laravel</title>

    <!-- jQuery UI CSS -->
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

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

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

    @livewireStyles
</head>
<body>

    <livewire:jqueryui-autocomplete />

    @livewireScripts

    @yield('scripts')
</body>
</html>

8. Output

View Output


9. Conclusion

Returning JSON Array response must have data with value and label keys otherwise, data will not load in autocomplete element.

You can also view this tutorial if you want to implement autocomplete without any library in Livewire.

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

Leave a Comment