Laravel 9 Typeahead Js Live Autocomplete Search Tutorial

Autocomplete or live search is the best feature, and it provides faster recommendations or suggestions to users as they start typing in.

The autocomplete tool helps users in many possible ways: search suggestion, product discovery, and getting data category wise; it performs every task simultaneously with utmost precision.

This Laravel autocomplete tutorial will teach you how to build autocomplete widget in a laravel application using the Typeahead js, Bootstrap 5 CSS framework.

If you want to build a powerful typeahead with a sturdy foundation, then typeahead js is the one you must need; it’s a javascript package that helps create an outstanding autocomplete component laravel.

You will create a laravel dynamic autocomplete search module, create a basic laravel app, create a model and migration, add test data into the database, fetch data from the database, and show data or records in the autocomplete in laravel.

How to Build Dynamic Autocomplete Search in Laravel 9 with Typeahead Js

  • Step 1: Download Laravel App
  • Step 2: Connect to Database
  • Step 3: Generate and Configure Controller
  • Step 4: Set Up Routes
  • Step 5: Create Table in Database
  • Step 6: Create Fake Records with Tinker
  • Step 7: Integrate Autocomplete in View
  • Step 8: View App in Browser

Download Laravel App

We want you to install the laravel app first. If you have already done then overlook this instruction. Else, run the given command.

composer create-project --prefer-dist laravel/laravel laravel-star-track

There after, get into app folder:

cd laravel-star-track

Connect to Database

A database connection is required; we primarily interact with a database to fetch the results, so add your database details in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Generate and Configure Controller

You have to generate the controller file, in this file we will accumulate all the functions within the single class.

php artisan make:controller SearchController

We have created the controller file; the file is ready to add the functions to load the autocomplete view template and handle the dynamic autocomplete search.

Add code in app/Http/Controllers/SearchController.php.

<?php

namespace App\Http\Controllers;

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


class SearchController extends Controller
{
    public function index()
    {
        return view('index');
    }
 
    public function typeaheadSearch(Request $request)
    {
          $dbQuery = $request->get('query');
          $output = User::where('name', 'LIKE', '%'. $dbQuery. '%')->get();
          return response()->json($output);
    } 
}

Set Up Routes

In this section, you will learn how to create routes to handle the data from the controller, create two routes with the help of the controller we created in the previous section.

Update routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;



Route::get('/dynamic-autocomplete-search', [SearchController::class, 'index']);
Route::get('/get-results', [SearchController::class, 'typeaheadSearch']);

Create Table in Database

Get ready to run the migration; create a user table in the database; you have to run the recommended command.

php artisan migrate

Create Fake Records with Tinker

You need some records in your database, you can use tinker factory to generate as many records as you want.

Type the given command to get into the tinker PSY shell and generate the dummy data.

php artisan tinker 

User::factory()->count(300)->create()

Integrate Autocomplete in View

All the imperatives tasks have been done; the only task we are left with is to define the blade view file. In the blade view, you will import Typeahead js and bootstrap 5 to bring dynamic autocomplete in action.

Create index.blade.php file in views folder, after that update the provided code in resources/views/index.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel Autocomplete Search with Typeahead JS Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" />
</head>

<body>

    <div class="container mt-4">
        <div classs="form-group">
            <input type="text" id="autocomplete" name="autocomplete" placeholder="Enter search text" class="form-control" />
        </div>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js">
    </script>
    <script>
        var route = "{{ url('get-results') }}";
        $('#autocomplete').typeahead({
            source: function (query, process) {
                return $.get(route, {
                    query: query,
                    classNames: {
                        input: 'Typeahead-input',
                        hint: 'Typeahead-hint',
                        selectable: 'Typeahead-selectable'
                    }
                }, function (d) {
                    console.log(d)
                    return process(d);
                });
            }
        });
    </script>

</body>

</html>

View App in Browser

Now, we will use the PHP artisan command with serve tag to start the application; if developing locally, use the url to view the app.

php artisan serve
http://localhost:8000/dynamic-autocomplete-search

Create Typeahead Js Autocomplete Search in Laravel

Conclusion

Have you seen how easy it was to implement Typeahead autocomplete in laravel? Well, after going through this tutorial, it certainly is. Autocomplete is a great tool to provide suggestions while they type into the input field.

Moreover, it helps your users to find the pre-populated records within fractions of seconds swiftly.

Not only but also it amplifies the user experience exponentially and brings unbound gratification to your users’ life. So, this was our pearl of wisdom for you, have a good day to you.