Laravel 11 JQuery UI Autocomplete Ajax Search Example

In Laravel 11, jQuery UI helps to develop autocomplete search using AJAX. It will auto populate suggestions when the user types in an input search box or textbox so that users can find relevant information quickly and efficiently.

In this tutorial guide, we will teach you how to develop an autocomplete search using jQuery UI Ajax in laravel 11 applications from database.

Steps on jQuery UI Autocomplete Search in Laravel using Ajax

Here are:

Step 1 – Download New Laravel Application

Open cmd or terminal window and type the following command into it to download new laravel application into your server:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Initialize Database with Application

So open the .env file and add the database detail like the following:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3 – Create Model and Migration

Run the php artisan make:model Task -m on cmd to create model and migration file:

php artisan make:model Task -m

Edit task.php from app/models folder and add the following code in it:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;

    protected $fillable = [
        'name'
    ];
}

And open create_tasks_tables.php from database/migration folder and add the following code into it:

    public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

    }    

Now run php artisan migrate to create tables into your configured database with the application.

php artisan migrate

Step 4 – Add Routes

Open web.php file from routes folder and add the following routes into it:

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TaskController;

Route::get('input-form', [TaskController::class, 'index']);
Route::get('search-autocomplete', [TaskController::class, 'searchAutocomplete']);

Step 5 – Create a Controller

Create a controller file to handle autocomplete search logic into it, use the following command for that:

php artisan make:controller TaskController

Open TaskController.php from app/http/controllers folders and create two methods into it; something like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Task;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('search-form');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function searchAutocomplete(Request $request)
    {
        $res = Task::select("name")
                ->where("name","LIKE","%{$request->term}%")
                ->get();

        return response()->json($res);
    }
}

Step 6 – Create Search Form

Navigate to resources/views folder and create blade view file name search-form.blade.php in it, then create search form in blade view file; something like this:

Then add the following code into search-form.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 jQuery UI AJAX Autocomplete Search Example - Tutsmake.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery UI CSS -->
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- jQuery UI -->
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script type="text/javascript">
        var siteUrl = "{{url('/')}}";
    </script>
</head>
<body>
<div class="container mt-4">
    <div class="card">
        <div class="card-header text-center font-weight-bold">
            <h2>Laravel 11 jQuery UI AJAX Autocomplete Search Example - Tutsmake.com</h2>
        </div>
        <div class="card-body">
            <form name="autocomplete-textbox" id="autocomplete-textbox" method="post" action="#">
                @csrf
                <div class="mb-3">
                    <label for="exampleInputEmail1" class="form-label">Search Task</label>
                    <input type="text" id="name" name="name" class="form-control">
                </div>
            </form>
        </div>
    </div>

</div>

</body>
</html>

Step 7 – Add jQuery UI and Ajax Code

Add JavaScript/jQuery UI code to handle the AJAX request and update the suggestions as the user types:

<script type="text/javascript">
     $(document).ready(function() {
    $( "#name" ).autocomplete({

        source: function(request, response) {
            $.ajax({
            url: siteUrl + '/' +"search-autocomplete",
            data: {
                    term : request.term
             },
            dataType: "json",
            success: function(data){
               var resp = $.map(data,function(obj){
                    return obj.name;
               });

               response(resp);
            }
        });
    },
    minLength: 2
 });
});

</script>

Step 8 – Run and Test Application

Run php artisan serve command on cmd to run application on localhost for testing:

 php artisan serve

Open browser with http://localhost:8000/input-form:

http://localhost:8000/input-form

Conclusion

We hope you have learned how to create autocomplete search application using jquery ui and ajax in laravel 11. This helps us to create autocomplete search functionality that provides suggestions to users as they type in the search input field or textbox.

Recommended Guides

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *