Thursday 22 July 2021

Autocomplete Search in Laravel 8 using Typeahead.js


Autocomplete or Live Search is nice functionality, because it has give us auto suggestion or recommendations, when we have start type in input field. If you have not know but Autocomplete feature has provide helps to User in different ways like auto search suggestion when we have search some specific product or some specific category. So when we have start type then it has provide suggestion which has fetch from database and display in autocomplete search suggestion dropdown list.

Under this Laravel 8 tutorial, we will implement Autocomplete Search by using Typeahead.js library. So this is Laravel 8 Autocomplete tutorial in which you can find how to add Autocomplete Search feature in Laravel 8 Application by using Typeahead JS with 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 which helps us to make an outstanding Autocomplete Search functionality in our Laravel 8 Application.

Now we have proceed for create Autocomplete Search Module in our Laravel 8 application. In this tutorial, we will create model and migration and add fake data in Mysql database and from that data we will fetch and display in autocomplete search suggestion 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 following steps.


Autocomplete Search in Laravel 8 using Typeahead.js

How to Implement Dynamic Autocomplete Search in Laravel using Typeahead.js


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

Step 1 : Download & 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.


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


This command will create typeahead_autocomplete directory and under that directory it will download latest version of Laravel framework. After download Laravel framework, then after we have go into typeahead_autocomplete this directory. For this we have to run following command in command prompt.


cd typeahead_autocomplete


Step 2 : Make 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=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 : Create User Table in Database


In third step, we have to create User table in Mysql database. So when we have download latest version of Laravel framework then by default User.php model class and users table migration file will be available under this 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 if you have create users table then under this steps we have to insert fake records under this table. For this we have to open database/seeders/DatabaseSeeder.php file and under this file we have to write following code.

database/seeders/DatabaseSeeder.php

<?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 under this users table in MySQL Database.


php artisan db:seed --force


Step 5 : Create Controller


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


php artisan make:controller TypeaheadAutocompleteController

This command will create TypeaheadAutocompleteController.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


After create controller class file, now in step six, we need to create index() method under this class. So this method will load typeahead_autocomplete.blade.php file in browser.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }
}
?>





Step 7 : Create Blade View File


In this step 7, we have need to create blade view file for display html output in browser. So here we have create typeahead_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 Laravel 8 app.


<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('typeahead_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 Controller class 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 TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_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 controller class. For set route, we have to open routes/web.php file and under this file first we need to import TypeaheadAutocompleteController.php class file and then after write code for set route.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TypeaheadAutocompleteController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/typeahead_autocomplete', [TypeaheadAutocompleteController::class, 'index']);

Route::get('/typeahead_autocomplete/action', [TypeaheadAutocompleteController::class, 'action'])->name('typeahead_autocomplete.action');


Step 10 : Start Development Server


Once we have follow all above step, so here our Laravel 8 application is ready with Autocomplete Search feature. So for check output in browser, first we have 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.


php artisan serve


Step 11 : Check Output in Browser


After start development server, now we want to check output in browser. So in browser we have hit following url for check Autocomplete Search in Laravel 8 application.


http://localhost:8000/typeahead_autocomplete


Conclusion


So under this tutorial, we have seen how easily we can implement Typeahead.js Autocomplete search in Laravel 8 framework. So making this Autocomplete Search feature, we have seen that it is very useful in our web application, because when we have type something then this feature has provide us suggestion related to text which we have type in input field, and user can get filter suggestion and from that suggestion user can select option.

0 comments:

Post a Comment