Autocomplete is a user-friendly way to display a large list of data on a page.
It shows suggestions based on the input and a user can select an option from the list.
In this tutorial, I show how you add jQuery UI autocomplete to an input field in the Laravel 7 project.
Contents
1. Create Table
- Create a new table
Employees
using migration and add some records.
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->bigIncrements('id'); $table->string('name'); $table->string('email'); $table->timestamps(); }); }
- Run the migration –
php artisan migrate
- The table is been created and add some records in it.
2. Download
- Download jQuery UI from its website and also download the jQuery library.
- Copy download files in
public/
folder. - I have copied jQuery UI library in
public/jqueryui/
folder.
3. Model
- Create
Employees
Model.
php artisan make:model Employees
- Specify mass assignable Model attributes – name, and email using the
$fillable
property.
Completed Code
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Employees extends Model { protected $fillable = [ 'name','email' ]; }
4. Route
- Open
routes/web.php
file. - Define 2 routes –
Route::get('/','EmployeesController@index'); Route::post('/employees/getEmployees/','EmployeesController@getEmployees')->name('employees.getEmployees');
- The 2nd route is used for AJAX request.
5. Controller
- Create
EmployeesController
Controller.
php artisan make:controller EmployeesController
- Open
app/Http/Controllers/EmployeesController.php
file. - Import
Employees
Model. - Create two methods –
- index() – Load
employees.index
view. - getEmployees() – This use to handle AJAX request. Read POST search value and assign in
$search
.
- index() – Load
If $search
is empty then select first 5 records from the employees
table otherwise use $search
in where
on the name
field and select first 5 records.
Loop on the fetched records. 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\Employees; class EmployeesController extends Controller { public function index(){ return view('employees.index'); } /* AJAX request */ 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); } }
6. View
Create file –
- Create a new folder
employees
atresources/views/
folder. - In
resources/views/employees/
folder create a newindex.blade.php
file.
Include CSS and JS –
- Specify
csrf_token()
in the<meta >
. - Include jQuery UI CSS, jQuery, and jQuery UI JS at the
<head >
section.
Input fields –
- Create two input fields.
- 1st is used to initialize jQuery UI autocomplete.
- 2nd is used to display the selected value from the autocomplete suggestion option.
Script –
- Read
csrf_token()
from meta tag and assign inCSRF_TOKEN
variable. - Initialize jQuery UI autocomplete on
#employee_search
field. - Using
source
option to send AJAX post request toroute('employees.getEmployees')
to fetch employees list for displaying. - Also, pass
CSRF_TOKEN
along with search value in thedata
. - On successful callback pass response in
response()
function. - Using
select
option to display selected optionlabel
in the#employee_search
andvalue
in#employeeid
input fields.
Completed Code
<!DOCTYPE html> <html> <head> <title>Make Autocomplete search using jQuery UI in Laravel 7</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" type="text/css" href="{{asset('jqueryui/jquery-ui.min.css')}}"> <!-- Script --> <script src="{{asset('jquery-3.3.1.min.js')}}" type="text/javascript"></script> <script src="{{asset('jqueryui/jquery-ui.min.js')}}" type="text/javascript"></script> </head> <body> <!-- For defining autocomplete --> <input type="text" id='employee_search'> <!-- For displaying selected option value from autocomplete suggestion --> <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('employees.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>
7. Output
8. Conclusion
I used POST in the AJAX request but you can also use GET request.
Initialize jQuery UI autocomplete on an input element and use the source
option to send AJAX request for displaying suggestions.
View this tutorial, to know jQuery UI autocomplete implementation in Laravel 8.
If you found this tutorial helpful then don't forget to share.