How to Create Autocomplete Search in Laravel 9 with Typeahead JS

In this comprehensive tutorial, let’s figure out how to create autocomplete search in Laravel 9 application. We will do this using the Typeahead JS library and Bootstrap 5.

Typeahead JavaScript is an eloquent library that is used to build autosuggest and autocomplete feature in Laravel applications.

This is an essential tool that provides suggestions at amazingly fast speed. Especially when users type a query in an autocomplete box.

This quick Laravel typeahead autocomplete tutorial is completely pragmatic, and also deals with every variation that is essential to create autosuggest in Laravel.

In this tutorial, we will cover all the significant ways that will help you fetch numerous records from a database and also implement in autocomplete search box.

Laravel 9 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: Apply Autocomplete Live Search in View
  • Step 7: Start Laravel Application

Create New Laravel Project

We will start with sharing the recommended command to install the latest version of your Laravel project.

Once you are done with this step, 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’s put in the database name, username and password in .env file to form the connection 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

If you are using MAMP local server in macOS, assure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Autocomplete Controller

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

php artisan make:controller TypeaheadController

As soon as the new controller file is created 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

Next, to make GET request route needs to be added in Laravel, this will help us show autocomplete component in view.

Moreover, to fetch data from database and inject 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 that is used to create test or fake data without moving heaven and earth. Therefore, run the command below to generate dummy records.

Firstly, run the Laravel migration.

php artisan migrate

Next, 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

Finally, we need to set up the view and integrate the autocomplete search, consequently make sure to import bootstrap, Typeahead JS and jQuery along with input text search box.

We can use default Laravel view template, so add the code below 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

Now open the terminal and execute the command below to start the Laravel application.

php artisan serve

Put the URL below in the address bar and hit enter to test your app.

http://localhost:8000/home
Laravel Typeahead Js Autocomplete Search

Conclusion

To conclude, Laravel 9 autocomplete search example is a guide from our side. In this tutorial, we have managed to share a simple look on how to create autocomplete search using Typeahead JS in Laravel.

Moreover, we also learnt how to get results from the database for autocomplete search.

Leave a Comment