jQuery UI Autocomplete Database Search Laravel 8

Reading Time: 7 minutes
6,249 Views

Inside this article we will see the concept of autocomplete search using jquery ui in Laravel 8. This autocomplete search will be total dynamic which searches data from database.

You will get the complete concept of jQuery UI Autocomplete Database Search Laravel 8.

Learn More –

This tutorial will use a complete basic idea to learn as well as to integrate in a very easy way. This will use jquery ui which binds autocomplete data set.

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

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

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Model and Migrations

Open project into terminal and run this command.

$ php artisan make:model Country -m

It will create two files –

  • Model file Country.php at /app/Models folder.
  • Migration file 2021_06_27_151155_create_countries_table.php at /database/migrations folder.

Open Migration file 2021_06_27_151155_create_countries_table.php and write this complete code into it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCountriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->char("iso", 2);
            $table->string("name", 50);
            $table->string("nicename", 50);
            $table->char("iso3", 3)->nullable();
            $table->smallInteger("numcode")->nullable();
            $table->integer("phonecode")->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('countries');
    }
}

Open Country.php model file and write this complete code into it.

<?php

namespace App\Models;

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

class Country extends Model
{
    use HasFactory;

    public $timestamps = false;
}

Run Migration

Back to terminal and run this command to run migration and create table.

$ php artisan migrate

It will run all migrations.


Insert Data into Table

As from migration we have created a table named as countries. We need some data into this table to test autocomplete search.

For data here we have the link of github.

Run the given mysql query to your database from this github link.

When you will run, you will get data something like this.


Create Controller

Back to terminal and run this command to create controller file.

$ php artisan make:controller SearchController

It will create SearchController.php file inside /app/Http/Controllers folder.

<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('search');
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(Request $request)
    {
        $input = $request->all();

        $data = Country::select(["id", "nicename"])
                ->where("nicename","LIKE","%{$input['query']}%")
                ->get();
   
      $countries = [];
      
      if(count($data) > 0){

            foreach($data as $country){
                $countries[] = array(
					"value" => $country->id,
					"label" => $country->nicename,
				);
            }
        }        
        return response()->json($countries);
    }
}

Add Routes

Open web.php file from /routes folder. Add these given routes into it.

//..

use App\Http\Controllers\SearchController;

Route::get('search', [SearchController::class, 'index'])->name('search');
Route::post('autocomplete', [SearchController::class, 'autocomplete'])->name('autocomplete');

//..

Download jQuery UI

  • Download the jQuery UI plugin from here.
  • Extract it in the public/ folder at the root.

You can also use CDN –

<!-- Script --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 

<!-- jQuery UI --> 
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Create Blade Layout File

Create search.blade.php file inside /resources/views folder.

Open search.blade.php and write this complete code into it.

<!DOCTYPE html>
<html>

<head>
    <title>Autocomplete Search From Database Laravel 8 Using jQuery UI</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <!-- jQuery UI CSS -->
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <!-- <link rel="stylesheet" type="text/css" href="/jquery-ui/jquery-ui.min.css"> -->

    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- jQuery UI JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <!-- <script type="text/javascript" src="/jquery-ui/jquery-ui.min.js"></script> -->
</head>

<body>

    <div class="container" style="margin-top: 40px;">
        <div class="panel panel-primary">
            <div class="panel-heading">Autocomplete Search From Database Laravel 8 Using jQuery UI</div>
            <div class="panel-body">
                <label>Search Country...</label>
                <input class="form-control" id="autocomplete_country" type="text">
                <br>
                <p>Country ID : <span id="countryId"></span></p>
            </div>
        </div>
    </div>

    <!-- Script -->
    <script type='text/javascript'>
        $(document).ready(function() {
            // Initialize
            $("#autocomplete_country").autocomplete({

                source: function(request, response) {

                    return $.post("{{ route('autocomplete') }}", {
                        query: request.term,
                        "_token": "{{ csrf_token() }}",
                    }, function(data) {
                        response(data);
                    });
                },
                select: function(event, ui) {
                    // Set selection
                    $('#autocomplete_country').val(ui.item.label); // display the selected text
                    $('#countryId').text(ui.item.value); // save selected id to input
                    return false;
                },
                focus: function(event, ui) {
                    $("#autocomplete_country").val(ui.item.label);
                    $("#countryId").text(ui.item.value);
                    return false;
                },
            });
        });
    </script>

</body>

</html>

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL – http://127.0.0.1:8000/search

We hope this article helped you to learn about jQuery UI Autocomplete Database Search Laravel 8 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.