jQuery UI hiện có rất nhiều tiện ích khác nhau, một trong số đó là chức năng gợi ý tự động hoàn thành Autocomplete. Dữ liệu sẽ được tải sau khi người dùng nhập các kí tự vào ô tìm kiếm, danh sách các kết quả phù hợp sẽ hiện lên để lựa chọn. Trong bài viết này, mình sẽ hướng dẫn các bạn cách áp dụng chức năng Autocomplete search sử dụng jQuery UI trên Laravel 8.
1. Config Database
Như thường lệ, bắt đầu mỗi project chúng ta phải kết nối với cơ sở dữ liệu, cấu hình tại file .env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=tutorial DB_USERNAME=root DB_PASSWORD=
2. Tạo cấu trúc bảng
Sử dụng migration để tạo bảng employees
php artisan make:migration create_employees_table
Tìm đến thư mục database/migrations/ trong dự án của bạn, tìm đến file có chứa create_employees_table, ở method up() hãy viết code như sau:
public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('username'); $table->string('name'); $table->string('email'); $table->timestamps(); }); }
Sau đó lưu lại và chạy lệnh
php artisan migrate
3. Tạo Model
Sử dụng câu lệnh dưới đây để tạo model có tên Employees
php artisan make:model Employees
- Điền các thông tin username, name, and email của bảng vừa tạo vào thuộc tính
$fillable
.
Như bên dưới
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Employees extends Model { use HasFactory; protected $fillable = [ 'username','name','email' ]; }
4. Tạo Controller
Chạy lệnh sau để tạo controller.
php artisan make:controller EmployeesController
Tạo 2 phương thức trong controller EmployeesController vừa tạo
- index() – Dùng để load file view.
- getEmployees() – Dùng để sử lý các yêu cầu về AJAX
Logic của controller sẽ như sau:
Gán giá trị tìm kiếm dạng POST vào biến $search
. Nếu $search
trống thì sẽ lấy 5 bản ghi từ bảng employees
và gán vào biến $employees
Nếu tồn tại biến $search
thì sẽ truy vấn dữ liệu từ bảng employees
theo cột name
. Các giá trị sau khi truy vấn sẽ gán vào biến $employees
Sử dụng vòng lặp với biến $employees
và khởi tạo biến $response
với value và label. Kết quả trả về dạng json
Code hoàn thành như sau:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Employees; class EmployeesController extends Controller { public function index(){ // Load index view return view('index'); } // Fetch records 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); } }
5. Tạo Router
- Mở file
routes/web.php
- tạo 2 route như sau:
- / – Tải file view.
- /getEmployees – Xử lý các yêu cầu AJAX.
Code hoàn thiện như sau:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\EmployeesController; Route::get('/', [EmployeesController::class, 'index']); Route::post('/getEmployees', [EmployeesController::class, 'getEmployees'])->name('getEmployees');
6. Tạo file view
Tạo 1 file mới có tên index.blade.php
trong thư mục resources/views/
HTML –
- Tạo thông báo CSRF trong thẻ
<meta >
- Tích hợp thư viện jQuery UI và jQuery
- Tạo 2 khối text –
- khối 1 sử dụng đẻ khởi tạo tính năng tự động hoàn thành
- Khối 2 sử dụng để hiển thị giá trị tương ứng
jQuery –
- Đọc giá trị
csrf_token
trong thẻ meta ở trên và gán vào biếnCSRF_TOKEN
- Khởi tạo phần tử
#employee_search
- Sử dụng
source
để load dữ liệu AJAX khi yêu cầu tới{{route('getEmployees')}}
. - Chuyển
CSRF_TOKEN
vàodata
. - Khi thành công, chuyển dữ liệu phản hồi tới function
response()
- Sử dụng thẻ
select
để hiển thị giá trị
Code hoàn thiện như sau:
<!DOCTYPE html> <html> <head> <title>How to make Autocomplete search using jQuery UI in Laravel 8</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" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> </head> <body> <!-- For defining autocomplete --> Search User : <input type="text" id='employee_search'> <br><br> <!-- For displaying selected option value from autocomplete suggestion --> Selected UserID : <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('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>
Như vậy là bạn đã hoàn thành xong các bước để thực hiện chức năng Autocomplete search sử dụng jQuery UI trên Laravel 8. Bạn có thể xem DEMO tại đây
Nếu có thắc mắc nào, hãy comment ngay bên dưới, mình sẽ tương tác với nhau cụ thể hơn