How to use Ajax Autocomplete Search using JQUERY UI in laravel 10

Spread the love

Hello Guys,

Explore the power of Laravel 10 Ajax Autocomplete Search with jQuery UI in this comprehensive example. Witness the seamless integration of jQuery UI’s autocomplete feature within Laravel 10. Learn how to implement an autocomplete input box effortlessly with jQuery UI. This tutorial leverages jQuery UI to demonstrate the simplicity of the Laravel 10 autocomplete textbox.

In this demonstration, we will guide you through the process of setting up a fresh Laravel 10 application, including creating a users table via migration. Utilizing Tinker, we’ll populate the database with mock user data. To tie it all together, we’ll create a straightforward Blade file and harness the capabilities of jQuery UI JS to build an autocomplete text box.

Let’s now look at the straightforward methods to finish this work for Ajax autocomplete search:

Step 1: Install Laravel 10

While it’s not mandatory, you may choose to execute the following command if you haven’t already set up your Laravel application:

Also Read: How to upload Images using LARAVEL 10

composer create-project laravel/laravel example-app

Step 2: Add Dummy Users

In order to facilitate a smooth database migration process, we’ve created a new user table. It’s essential to run the migration command after executing the default migrations.

Also Read: how to use Cron Job Task Scheduling using LARAVEL 10

php artisan migrate

Let’s employ Tinker Factory for generating dummy users. You can use the following command to create simulated user records:

php artisan tinker
  
User::factory()->count(20)->create()

Step 3: Create a Controller

It’s time to create a new SearchController in your project. This controller will feature two essential methods: one for handling AJAX requests with JSON responses and another for rendering view responses. Below, you’ll find the content that should be included in the controller file.

Also Read: Model Events Example in LARAVEL 10

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('searchDemo');
    }
      
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(Request $request): JsonResponse
    {
        $data = User::select("name as value", "id")
                    ->where('name', 'LIKE', '%'. $request->get('search'). '%')
                    ->get();
      
        return response()->json($data);
    }
}

Step 4: Create Routes

In this phase, it is essential to set up a route for your datatables layout file and another one for data retrieval. To achieve this, follow these steps to add the required route by editing your ‘routes/web.php‘ file.

Also Read: How to install Docker on Windows 10/11 STEP BY STEP

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 a View File

To complete the process, you should create the searchDemo.blade.php file, located at resources/views/searchDemo.blade.php. This file is designed with a layout and displays a comprehensive list of items.

Also Read: How To Generate Invoice PDF In Laravel 10

resources/views/searchDemo.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 JQuery UI Autocomplete Search Example - itcodestuff.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 - itcodestuff.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:

Once you’ve successfully completed all the essential prerequisites, it’s time to execute the following command and hit Enter to initiate the Laravel application:

php artisan serve

To access the app’s output, simply input the provided URL into your web browser.

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

http://localhost:8000/demo-search

Discover the best in Laravel blog through our thoughtfully crafted content.

Leave a Comment