DEV Community

Cover image for How to Implement an Autocomplete Typeahead Search Feature in Laravel
kkumar-gcc
kkumar-gcc

Posted on • Originally published at kkumar-gcc.Medium

How to Implement an Autocomplete Typeahead Search Feature in Laravel

Laravel is a popular open-source PHP framework that is widely used for building web applications. It provides a lot of features and functionalities that make web development easier and faster. One of these features is the Typeahead search, also known as Autocomplete search.

Autocomplete search is a feature that helps users to find the desired content by suggesting possible options as they type. It is a useful tool that can make the search process more intuitive and convenient for the users. In this article, we will explore how to implement the Typeahead search in Laravel.

Prerequisites

Before we start, make sure that you have a Laravel project setup. If you don't, you can follow the Laravel installation guide. You also need to have basic knowledge of HTML, CSS, JavaScript, and PHP.

Implementing Typeahead search in Laravel

To implement the Typeahead search in Laravel, we need to create a search form and a controller to handle the search requests. We will also use the Typeahead library to display the search suggestions.

Step 1: Installing Typeahead library

To install the Typeahead library, we can use a package manager like npm. Open the terminal and navigate to your Laravel project directory. Run the following command to install the jQuery Typeahead plugin:

npm install jquery-typeahead
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating a search form

To create a search form, we will use the HTML form element. Open resources/views/welcome.blade.php file and add the following code:

<head>
    //......

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.2/jquery.typeahead.css"
        integrity="sha512-zPDjm5fHC6JUi5jEnhJetvp1zLvc1Dd5TuMFQQtqRH0KpOzrng4vHiFu2Eva+Xgu7umz0lqGHkmGjUYdeSW54w=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.2/jquery.typeahead.js"
        integrity="sha512-8+3AF+qMeZ3HSeKKru1YD5pFbXnIxUvMH1UsK8sKbHwbj5ZixBtDP+8oMMkBeaZc8TIIOjHnxN++zCPhHWCrMQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
  // .....

  <form action="{{ url('search') }}" method="GET">
     <div class="typeahead__container">
          <div class="typeahead__field">
               <div class="typeahead__query">
                    <input class="typeahead"
                                 name="query"
                                 autocomplete="off">
                </div>
                <div class="typeahead__button">
                     <button type="submit">
                             <span class="typeahead__search-icon"></span>
                     </button>
                </div>
           </div>
     </div>
  </form>

  //....

  @vite(['resources/js/app.js'])

</body>
Enter fullscreen mode Exit fullscreen mode

In the code above, we have created a form with a text input field and a submit button. The input field has a typeahead class that we will use in the next step to initialize the Typeahead library.

Step 3: Initializing Typeahead library

To initialize the Typeahead library, we will use the JavaScript code. Open the public/js/app.js file and add the following code:

import $ from "jquery";
import "jquery-typeahead";

$(function () {
    $.typeahead({
        input: ".typeahead",
        hint:true,
        minLength:2,// default
        source: {
            groupName: {
                // Ajax Request
                ajax:  function (query) {
                    return {
                        type: "GET",
                        url: "/search/suggestions",
                        data: {
                            query: "{{query}}"
                        },
                        callback: {
                            done: function (data) {
                                return data;
                            }
                        }
                    }
                }
            }
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

In the code above, we have used the jQuery $(function () {} function to make sure that the Typeahead library is initialized after the page has loaded. We have also used the $.typeahead() function to initialize the Typeahead library on the text input field with the typeahead class.
We have also passed an object with some configuration options to the typeahead function. The options are:

  • hint: This option is set to true so a suggestion text will appear if there is an item inside the result list that starts by the user query, also pressing the right arrow at the end of the search input text will autocomplete the query with the suggested hint.
  • highlight: This option is set to true to highlight the matching part of the suggestion.
  • minLength: This option sets the minimum number of characters that need to be typed before the suggestions start appearing.
  • source : The source option corresponds to the data set(s) that Typeahead will look through to find matches for the user query string.Inside the source, you can have multiple lists of data (groups) . You can config source.group:
    • ajax : This function makes an AJAX request to the /search/suggestions endpoint with the query to get the suggestions.

Step 4: Creating a controller

To handle the search requests, we need to create a controller. Run the following command to create a controller:

php artisan make:controller SearchController
Enter fullscreen mode Exit fullscreen mode

This command will create a SearchController class in the app/Http/Controllers directory. Open the app/Http/Controllers/SearchController.php file and add the following code:

<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->input('query');
        $products = Product::where('name', 'like', "%$query%")->get();

        return view('search', compact('products'));
    }

    public function suggestions(Request $request)
    {
        $query = $request->input('query');
        $suggestions = Product::where('name', 'like', "%$query%")->pluck('name');

        return response()->json($suggestions);
    }
}
Enter fullscreen mode Exit fullscreen mode

We are looking in the Product model (used in the previous blog). You are free to use any other model you choose.

In the code above, we have created two methods in the SearchController class. The index method handles the search requests and retrieves the products with names that match the query. The suggestions method returns the suggestions for the Typeahead search.

Step 5: Creating routes

To map the search form to the SearchController class, we need to create routes. Open the routes/web.php file and add the following code:

Route::get('/', function () {
    return view('welcome');
});
Route::get('search', [SearchController::class,'index']);
Route::get('search/suggestions', [SearchController::class,'suggestions']);
Enter fullscreen mode Exit fullscreen mode

In the code above, we have created two routes. The first route maps the / endpoint to the home view. The second route maps the search endpoint to the index method of the SearchController class. The third route maps the search/suggestions endpoint to the suggestions method of the SearchController class.

Step 6: Creating a view

To display the search results, we need to create a view. Create a new file resources/views/search.blade.php and add the following code:

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($products as $product)
            <tr>
                <td>{{ $product->id }}</td>
                <td>{{ $product->name }}</td>
                <td>{{ $product->price }}</td>
            </tr>
        @endforeach
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

In the code above, we have created a table to display the search results. The $products variable contains the search results that are passed from the SearchController class. The @foreach loop iterates through the $products array and displays the product information in the table.

Step 7: Testing the application

Finally, we are ready to test the application. Start the development server by running the following command:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Open a web browser and go to http://localhost:8000. You should see the Typeahead search form. Start typing in the search form, and you should see the suggestions appear below the input field. Select a suggestion, and you should be redirected to the search results page that displays the matching products.

Conclusion

In this tutorial, we have learned how to implement a Typeahead search feature in Laravel. We have used the jQuery Typeahead plugin and created a search form, a controller, routes, and a view to handle the search requests and display the results. By following the steps in this tutorial, you should be able to implement a Typeahead search feature in your own Laravel applications.

Top comments (0)