Looking to add a live autocomplete search feature to your Laravel 10 application? You’re in luck! This article can help you implement this amazing feature using Livewire and without any need to worry about Alpine.js. With the new autocomplete search, users can find information quickly and easily for an enhanced user experience.
To start, the reader will be guided through a step-by-step process for setting up the necessary components. First, creating 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. Real-time suggestions are handled smoothly by Livewire, eliminating unnecessary struggles with searching. A user-friendly view will be created to showcase the beauty of both the search box and its results; no need to worry about leaving anyone hanging.
By the end of this tutorial, readers will discover a fully functional autocomplete search feature perfectly aligned with their Laravel 10 application. The best part? No Alpine.js or client-side JavaScript is necessary! Livewire’s impressive capabilities create an exceptionally smooth and fast autocomplete search experience for your Laravel app. Join us on this exciting journey as we get started!
Contents
- Creating the Database Table
- Creating the Model
- Creating the Controller
- Creating the Routes
- Create Livewire Component
- Creating the View
- Output
- Conclusion
1. Creating the Database Table
Create a database table named employees
using Laravel’s built-in migration feature. In order to do this, open 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 creating the employees
table, the next step is to generate a model 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 theemployees
table where$this->search
matches are in thename
field.
- searchResult() – This method calls when type characters in the textbox. If
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. Assignfalse
to$this->showresult
.
- fetchEmployeeDetail() – This method calls when select an item from the search result. Select a record by id from the
<?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'
andwire:keyup
event that callssearchResult
. - If
$showresult
istrue
then show search result in<ul>
. Loop on$records
to create<li >
. Addwire:click
event thatfetchEmployeeDetail({{ $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
8. Conclusion
Congratulations! You have successfully created a live autocomplete search feature using Livewire in Laravel. This real-time search enables users to look for employee names swiftly and presents a list of suggestions based on the input. Thanks to this functionality, user experience is significantly improved and searching for information becomes more efficient. 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.