How to Create Autocomplete Search in Laravel 8 with Typeahead Js

Last updated on: by Editorial Team

In this comprehensive tutorial you will figure out how to create autocomplete search in Laravel 8 application using the Typeahead Js library and Bootstrap 5.

Typeahead Js is an eloquent javascript library is profoundly used for building autosuggest and autocomplete feature in an application. It is an essential tool and provides suggestions at blazingly fast speed especially when users starts typing a query in autocomplete box.

This quick laravel typeahead autocomplete example is completely pragmatic that deals with every nuance essential for creating autosuggest in laravel. We will cover all the significant know hows which will help you fetch innumerable records from the database and implement in autocomplete search box.

Laravel 8 Typeahead Js Autocomplete Search Example

  • Step 1: Create New Laravel Project
  • Step 2: Add Database Details in ENV
  • Step 3: Create Autocomplete Controller
  • Step 4: Register New Route
  • Step 5: Create Test Records in Database
  • Step 6: Implement Autocomplete Live Search in View
  • Step 7: Start Laravel Application

Create New Laravel Project

The first section starts with sharing the recommended command for installing the latest version of laravel project.

If you are done with this step in advance, then move to the subsequent step.

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

Head over to project’s root:

cd laravel-cosmic-demo

Add Database Details in ENV

Let us put in database name, username and password in .env file to form the consensus between laravel and database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

Create Autocomplete Controller

It is imperative to create the new controller, in this file we will define the function that handles the autocomplete live search.

php artisan make:controller TypeaheadController

As soon as the new controller file manifested in the laravel project, make your way towards the newly generated file.

Then, add the code in app/Http/Controllers/TypeaheadController.php file.

<?php

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

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

Register New Route

Now, in order to make GET request route needs to be added in Laravel, it will help us showing autocomplete component in view.

Also for fetching data from database and injecting in typeahead autocomplete component, make sure to add given code in routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/home', [TypeaheadController::class, 'index']);

Route::get('/autocomplete-search', [TypeaheadController::class, 'autocompleteSearch']);

Create Test Records in Database

Laravel Tinker is the sound service primarily used for creating test or fake data without moving heaven and earth, hence run command to generate the dummy records.

First, run the laravel migration.

php artisan migrate

Immediately after use tinker command through the terminal to generate the dummy records.

php artisan tinker 

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

Implement Autocomplete Live Search in View

In the final section, we need to set up the view and integrate the autocomplete search, consequently make sure to improt bootstrap, Typeahead js and jQuery along with input text search box.

We can use default laravel view template, so add the code in welcome.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel Typeahead JS Autocomplete Search</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" />
    <style>
        .container {
            max-width: 600px;
        }
    </style>
</head>

<body>

    <div class="container mt-5">
        <div classs="form-group">
            <input type="text" id="search" name="search" placeholder="Search" 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 type="text/javascript">
        var route = "{{ url('autocomplete-search') }}";

        $('#search').typeahead({
            source: function (query, process) {
                return $.get(route, {
                    query: query
                }, function (data) {
                    return process(data);
                });
            }
        });
    </script>

</body>

</html>

Start Laravel Application

Lastly, open the terminal and execute the command to start the laravel application.

php artisan serve

Put the following url in the address bar and hit enter to test the app.

http://localhost:8000/home

Laravel Typeahead Js Autocomplete Search

Conclusion

The Laravel 8 autocomplete search example guide is done from our side; in this tutorial, we managed to share a simple outlook on how you can create autocomplete search using the profound Typeahead js in laravel. Apart from that, we also learned how to get results from the database for autocomplete search.

We managed to kill the two birds from the same stone, and we believe you have comprehended everything with our pragmatic approach.