Make Live Autocomplete Search with Livewire in Laravel

With the use of autocomplete textbox user can search and pick an item from the suggestion list.

Suggestion list is dynamically updated according to the input.

In this tutorial, I show how you can make autocomplete search with livewire in Laravel.

Make Live Autocomplete Search with Livewire in Laravel


Contents

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

1. Install Livewire

You can skip this step if Livewire is already installed in your project.

Run following command to install Livewire –

composer require livewire/livewire

2. 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=

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

4. Create Model

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

5. Create Controller

Create EmployeesController controller.

php artisan make:controller EmployeesController

Create 1 method –

  • index() – Load index view.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

6. Create Route

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

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmployeesController;

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

7. Create Livewire Component

Create fetchemployees component –

php artisan make:livewire searchbox

This will create 2 files –

  • app/Http/Livewire/Searchbox.php
  • resources/views/liverwire/searchbox.blade.php

Searchbox.php

  • Open app/Http/Livewire/Searchbox.php file.
  • Create 4 property variables –
    • $showresult – Using this toggle the suggestion list container.
    • $search – For data binding.
    • $records – Store fetched records.
    • $empDetails – Store clicked employee data.
  • Create 2 methods –
    • searchResult() – This method calls when type characters in the textbox. If $this->search is not empty then fetch 5 records from the employees table where $this->search matches are in the name field.

Assign fetched records to $this->records and assign true to $this->showresult.

If $this->search is empty then assign false to $this->showresult.

    • fetchEmployeeDetail() – This method calls when select an item from the search result. Select a record by id from the employees table and assign to $this->records. Update $this->search value with employee name. Assign false to $this->showresult.

Completed Code

<?php

namespace App\Http\Livewire;

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

class Searchbox extends Component
{
     public $showdiv = false;
     public $search = "";
     public $records;
     public $empDetails;

     // Fetch records
     public function searchResult(){

         if(!empty($this->search)){

             $this->records = Employees::orderby('name','asc')
                       ->select('*')
                       ->where('name','like','%'.$this->search.'%')
                       ->limit(5)
                       ->get();

             $this->showdiv = true;
         }else{
             $this->showdiv = false;
         }
     }

     // Fetch record by ID
     public function fetchEmployeeDetail($id = 0){

         $record = Employees::select('*')
                     ->where('id',$id)
                     ->first();

         $this->search = $record->name;
         $this->empDetails = $record;
         $this->showdiv = false;
     }

     public function render(){ 
         return view('livewire.searchbox');
     }
}

searchbox.blade.php

  • Open resources/views/liverwire/searchbox.blade.php file.
  • Create a text element for searching. Add wire:model='search' and wire:keyup event that calls searchResult.
  • If $showresult is true then show search result in <ul>. Loop on $records to create <li >. Add wire:click event that fetchEmployeeDetail({{ $record->id }}). Pass employee id as a parameter.
  • Display selected employee information in <div > is $empDetails if not empty.

Completed Code

<div>
    <!-- CSS -->
    <style type="text/css">
    .search-box .clear{
        clear:both;
        margin-top: 20px;
    }

    .search-box ul{
        list-style: none;
        padding: 0px;
        width: 250px;
        position: absolute;
        margin: 0;
        background: white;
    }

    .search-box ul li{
        background: lavender;
        padding: 4px;
        margin-bottom: 1px;
    }

    .search-box ul li:nth-child(even){
        background: cadetblue;
        color: white;
    }

    .search-box ul li:hover{
        cursor: pointer;
    }

    .search-box input[type=text]{
        padding: 5px;
        width: 250px;
        letter-spacing: 1px;
    }
    </style>

    <div class="search-box">
        <input type='text' wire:model="search" wire:keyup="searchResult">

        <!-- Search result list -->
        @if($showresult)
            <ul >
                @if(!empty($records))
                    @foreach($records as $record)

                         <li wire:click="fetchEmployeeDetail({{ $record->id }})">{{ $record->name}}</li>

                    @endforeach
                @endif
            </ul>
        @endif

        <div class="clear"></div>
        <div >
            @if(!empty($empDetails))
                <div>
                     Name : {{ $empDetails->name }} <br>
                     Email : {{ $empDetails->email }}
                </div>
            @endif
        </div>
    </div>

</div>

8. Create View

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

Include searchbox component and @livewireScripts.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Make Live Autocomplete Search with Livewire in Laravel</title>

   @livewireStyles
</head>
<body>

   <livewire:searchbox />

   @livewireScripts
</body>
</html>

9. Output

View Output


10. Conclusion

In the example, I created a custom component to add search box with a suggestion list. Data load while typing.

Customize the design and functionality according to your requirement while implementing this on your project.

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

Leave a Comment