Laravel 8 Database AutoComplete Search Using Typeahead

Reading Time: 6 minutes
4,271 Views

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

You will get the complete concept of Laravel 8 database autocomplete search using typeahead.

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 typeahead jquery plugin 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("nicename")
                ->where("nicename","LIKE","%{$input['query']}%")
                ->get();
   
      $countries = [];
      
      if(count($data) > 0){

            foreach($data as $country){
                $countries[] = $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::get('autocomplete', [SearchController::class, 'autocomplete'])->name('autocomplete');

//..

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</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js">
    </script>
</head>

<body>

    <div class="container" style="margin-top: 40px;">
        <div class="panel panel-primary">
            <div class="panel-heading">Laravel 8 Autocomplete Search</div>
            <div class="panel-body">
                <label>Search here...</label>
                <input class="typeahead form-control" type="text">
            </div>
        </div>
    </div>

    <script type="text/javascript">
        var path = "{{ route('autocomplete') }}";
        $('input.typeahead').typeahead({
            source: function(query, process) {
                return $.get(path, {
                    query: query
                }, function(data) {
                    return process(data);
                });
            }
        });

    </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 Laravel 8 database autocomplete search using typeahead 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more