Laravel 10,To implement jQuery UI Ajax autocomplete search in Laravel, you need to follow these steps:
Step 1: Install Laravel App
composer create-project laravel/laravel TypeaheadSearch
run default migrations
php artisan migrate
Step 2: Add Dummy Users
php artisan tinker
User::factory()->count(20)->create()
Step 3: Create Controller
app/Http/Controllers/SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
class SearchController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('AutoSearch');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function autocomplete(Request $request): JsonResponse
{
$data = User::select("name")
->where('name', 'LIKE', '%'. $request->get('query'). '%')
->get();
return response()->json($data);
}
}
Step 4: Create Routes
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(SearchController::class)->group(function(){
Route::get('demo-search', 'index');
Route::get('autocomplete', 'autocomplete')->name('autocomplete');
});
Step 5: Create Blade File
resources/views/AutoSearch
.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 JQuery UI Autocomplete Search Example - webthestuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div class="container">
<h1>Laravel 10 JQuery UI Autocomplete Search Example - webthestuff.com</h1>
<input class="typeahead form-control" id="search" type="text">
</div>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$( "#search" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: path,
type: 'GET',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#search').val(ui.item.label);
console.log(ui.item);
return false;
}
});
</script>
</body>
</html>
Run Laravel App:
php artisan serve
Now, Go to web browser, type the given URL and see the output:
http://localhost:8000/demo-search