DarkWebCode is a place where you can find a lot of exciting and inspiring stuff about Web Development, Blogging, SEO and many more

Breaking

How to Implement Dynamic Autocomplete Search in Laravel 8

How to Implement Dynamic Autocomplete Search in Laravel 8

Autocomplete or Live Search is a good functionality because it has given us autosuggestion or recommendations when we have start type in the input field. If you have not known but Autocomplete feature has provided helps Users in different ways like auto search suggestions when we have searched some specific product or some specific category. So when we have start type then it has provided suggestion which has to fetch from database and display in autocomplete search suggestion dropdown list. Under this Laravel 8 tutorial, we will implement Autocomplete Search by using the Typeahead.js library. So this is Laravel 8 Autocomplete tutorial in which you can find how to add Autocomplete Search feature in the Laravel 8 Application by using Typeahead JS with the Mysql database.


If you want to make Autocomplete Search feature for your web application, then typeahead.js is the best solution. Typeahead.js is a JavaScript library that helps us to make an outstanding Autocomplete Search functionality in our Laravel 8 Application.

In this tutorial, we will create a model and migration and add fake data in the Mysql database, and from that data, we will fetch and display in autocomplete search suggestions in our Laravel 8 application. So here we will build dynamic Autocomplete Search in Laravel 8 using Typeahead JS. For this, you have to follow the following steps.

  1. Install Laravel Framework
  2. Configure Database Connection
  3. Create User Table in Database
  4. Generate Fake Records
  5. Create Controller
  6. Create index() method in Controller
  7. Create Blade View File
  8. Create action() method in Controller
  9. Set Routes for Controller Method
  10. Start Development Server and Check Output in Browser

Step 1 : Install Laravel Framework

For build Autocomplete search feature, first we want to install latest version of Laravel framework. For this we have go to command prompt and run following command

laravel new Autocomplete-application

After installing Laravel framework, we have to open Autocomplete-application directory. For this we have to run following command in command prompt.

cd Autocomplete-application

Step 2 : Configure Database Connection

In second step we have make Mysql Database connection with our Laravel 8 application. For this we have to open .env file and under this we have to define MySQL credential which you can seen below

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=autocomplete
DB_USERNAME=root
DB_PASSWORD=

Step 3 : Create User Table in Database

In third step, we have to create User table in Mysql database.By default User.php model class and users table migration file will be available in Laravel framework. So for create users we have to go command prompt and run following command. This command will create users table in MySQL database.

php artisan migrate

Step 4 : Generate Fake Records

Once users table created, then we have to insert fake records this table for testing purpose otherwise we need to enter user table data manuvally.For this we have to open database/seeders/DatabaseSeeder.php file and under this file we have to write following code.

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        User::factory(100)->create();
    }
}
?>

After this we have open command prompt and run following command. This command will insert 100 fake data into users table in MySQL Database.

php artisan db:seed --force

Step 5 : Create Controller

In fifth steps, we have to create a controller in our Laravel framework. For this we have to open command prompt and fun following command.

php artisan make:controller AutocompleteController

This command will create AutocompleteController.php controller class file in app/Http/Controllers folder. Under this file first we want to import User models class. For this we have to write following code at header of this class file.

use App\Models\User;

Step 6 : Create index() method in Controller

In step six, we need to create index() method under AutocompleteController.php. So this method will load autocomplete.blade.php (we will create autocomplete.blade.php file in next step) view file in browser.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class AutocompleteController extends Controller
{
    function index()
    {
        return view('autocomplete');
    }
}
?>

Step 7 : Create Blade View File

In step seven, we need to create blade view file for display html output in browser. So that we have to create autocomplete.blade.php under resources/views directory. In the blade view, we need to import Typeahead js and bootstrap 4 library for make autocomplete in our project. After creating autocomplete.blade.php file, add the following HTML code in this file file

  
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Typeahead JS Live Autocomplete Search in Laravel 8</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" ></script>
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">Typeahead JS Live Autocomplete Search in Laravel 8</h1>
            <br />
            <input type="text" name="user_name" id="user_name" class="form-control-lg" placeholder="Enter User Name..." />
        </div>
    </body>
</html>
<script>
var path = "{{ url('autocomplete/action') }}";
$('#user_name').typeahead({
    source: function(query, process){
        return $.get(path, {query:query}, function(data){
            return process(data);
        });
    }
});
</script>
  

Step 8 : Create action() method in Controller

In steps 8, we have to crate action() method in AutocompleteController Controller file. Because this method will received ajax request from typeahead.js for fetch match data from database, and this method will send data to ajax request in JSON format.

<php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class AutocompleteController extends Controller
{
    function index()
    {
        return view('autocomplete');
    }
    function action(Request $request)
    {
        $data = $request->all();
        $query = $data['query'];
        $filter_data = User::select('name')
                        ->where('name', 'LIKE', '%'.$query.'%')
                        ->get();
        return response()->json($filter_data);
    }
}
?>

Step 9 : Set Routes for Controller Method

In steps 9, we need to set route for two method of AutocompleteController. For set route, we have to open routes/web.php file and under this file first we need to import AutocompleteController.php controller and then write code for set route.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AutocompleteController;
Route::get('/', function () {
    return view('welcome');
});
Route::get('/autocomplete', [AutocompleteController::class, 'index']);
Route::get('/autocomplete/action', [AutocompleteController::class, 'action'])->name('autocomplete.action');
?>

Step 10 : Start Development Server and Check Output in Browser

Once completed all the above steps, now we can check output in browser, so that, first we need to start Laravel development server. For this we have to open command prompt and run following command. This command will start server and provide us base url of our Laravel application. Then enter the base url with our route (http://127.0.0.1:8000/autocomplete) on browser and test our application.

php artisan serve