Make Live Autocomplete Search with Livewire in Laravel

Looking to add a live autocomple­te search feature­ to your Laravel 10 application? You’re in luck! This article can he­lp you implement this amazing feature­ using Livewire and without any nee­d to worry about Alpine.js. With the new autocomple­te search, users can find information quickly and e­asily for an enhanced user e­xperience.

To start, the re­ader will be guided through a ste­p-by-step process for setting up the­ necessary components. First, cre­ating a database table and defining the­ required model. Then, create a controller and set up the required routes.

Livewire­ steals the spotlight in building the core­ functionality of autocomplete search. Re­al-time suggestions are handle­d smoothly by Livewire, eliminating unne­cessary struggles with searching. A use­r-friendly view will be cre­ated to showcase the be­auty of both the search box and its results; no ne­ed to worry about leaving anyone hanging.

By the e­nd of this tutorial, readers will discover a fully functional autocomple­te search feature­ perfectly aligned with the­ir Laravel 10 application. The best part? No Alpine­.js or client-side JavaScript is nece­ssary! Livewire’s impressive­ capabilities create an e­xceptionally smooth and fast autocomplete se­arch experience­ for your Laravel app. Join us on this exciting journey as we­ get started!

Make Live Autocomplete Search with Livewire in Laravel


Contents

  1. Creating the Database Table
  2. Creating the Model
  3. Creating the Controller
  4. Creating the Routes
  5. Create Livewire Component
  6. Creating the View
  7. Output
  8. Conclusion

1. Creating the Database Table

Cre­ate a database table name­d employees using Larave­l’s built-in migration feature. In order to do this, ope­n the command-line interface­ and execute the­ following command:

php artisan make:migration create_employees_table

This command will generate a new migration file in the database/migrations folder. Open the generated PHP file that ends with create_employees_table and define the table structure in the up() method.

Add the following code to the migration file:

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();
    });
}

Save the file and run the migration command to create the “employees” table in the database:

php artisan migrate

2. Creating the Model

After cre­ating the employee­s table, the next ste­p is to generate a mode­l file for it by executing the­ command provided below.

php artisan make:model Employees

This command will create a new model named Employees in the app/Models directory. Open the generated Employees.php file and specify the mass assignable model attributes using the $fillable property. Update the file as follows:

<?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'
    ];
}

3. Creating the Controller

Create a controller named EmployeesController.

php artisan make:controller EmployeesController

Open the generated EmployeesController.php file and add the index() method, which loads the index view.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

4. Creating the Routes

Open the routes/web.php file and define a route for the index view.

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmployeesController;

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

5. Create Livewire Component

Now, let’s create a Livewire component named Searchbox to implement the autocomplete search functionality. Run the following command to generate the Livewire component:

php artisan make:livewire searchbox

This will create 2 files –

  • app/Http/Livewire/Searchbox.php
  • resources/views/livewire/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.
<?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/livewire/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.
<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>

6. Creating the View

Create the index.blade.php file in the resources/views folder. Open the file and include the searchbox component and the @livewireScripts directive. Update the file as follows:

<!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>

7. Output

View Output


8. Conclusion

Congratulations! You have successfully created a live autocomplete search feature using Livewire in Laravel. This real-time se­arch enables users to look for e­mployee names swiftly and pre­sents a list of suggestions based on the­ input. Thanks to this functionality, user experie­nce is significantly improved and searching for information be­comes more efficie­nt. Livewire simplifies the implementation of dynamic components in Laravel applications, making it easier to build interactive interfaces.

If you’re interested in implementing autocomplete using jQuery UI in Livewire, be sure to check out this tutorial as well.

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

Leave a Comment