Autocomplete Search Ajax Typeahead from Database in Laravel

Sovary August 23, 2022 561
4 minutes read

You have ever seen when typing in Google search bar will drop down suggest list of keywords. This is make user convenient to fill in their searching words. In this article I will show you how to create autocompleted search from database to filled in search box. You will learn step by step with source code example below to make autocompleted function in Laravel easily. 

What you need to be ready is you must have knowledge how to implement Laravel framework not very advanced but basic, and front-end with Ajax request background without reload the whole webpage. We will use jQuery ajax to request manipulate data from database and using Bootstrap Typeahead JS provide a good UI for dropdown suggest list autocompleted data.

Autocomplete Search Ajax

These following steps help you to create autocompleted in Laravel application:

  • Step 1 - Install Laravel
  • Step 2 - Migrate & Generate Dummy Users
  • Step 3 - Create Controller File
  • Step 4 - Add Route URL
  • Step 5 - Create Blade File
  • Step 6 - Run Laravel Server

Step 1 - Install Laravel

Firstly we are going to install Laravel which you have to connect to internet and installed composer. You may read how to configure database connection and installation in the article. I already wrote very simple to understand, but if you ready please skip to the next step. 

Step 2 - Migrate & Generate Dummy Users

In this step, we are not going to create new model because in Laravel has built-in user generated. We are going to run migration command to create table in database.

php artisan migrate

If you successfully execute the command then we will create dummy data in database table user with below command, I will create 33 sample users

php artisan tinker
User::factory()->count(33)->create()

Step 3 - Create Controller File

At this step we are going to create new controller file to handle request Ajax and point to view (blade), and we will implement two methods as well. Let's execute following command to generate a controller file.

php artisan make:controller SearchController

Then the file will create in directory Controllers

Open file app -> Http -> Controllers -> SearchController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class SearchController extends Controller
{
    // To point blade file which named index
    public function index()
    {
        return view('index');
    }
    
    // To search similar words and return 10 or less users
    public function suggestUser(Request $request)
    {
        $data = User::select("username")
                    ->where('username', 'LIKE', '%'. $request->get('q'). '%')
                    ->limit(10)
                    ->get();
        return response()->json($data);
    }
}

Step 4 - Add Route URL

Now we will add route for request via Ajax data and other is to render HTML data for view UI. Let's open the route file and modified as below code.

Open file routes -> web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(SearchController::class)->group(function()
{
    Route::get('/index', 'index');
    Route::get('/suggest', 'suggestUser')->name('autoComplete');
});

Step 5 - Create Blade File

This step we will design web UI which to input and display autocompleted dropdown suggest user in textbox with Bootstrap TypeaHead JS.

Create file resources -> views -> index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Autocomplete Suggestion - CamboTutorial.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="http://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>
</head>
<body>
     
<div class="container">
    <h1>Laravel 9 Autocomplete Dropdown from Database - CamboTutorial.com</h1>   
    <input class="typeahead form-control" id="search" type="text">
</div>
     
<script type="text/javascript"> 
    $('#search').typeahead({
      source: (query, process) =>
      {
        return $.get("{{ route('autoComplete') }}",
        {
            q: query
        },(data) =>
        {
            return process(data);
        });
      }
    });
  
</script>
     
</body>
</html>

Step 6 - Run Laravel Server

Before run this application make sure you database have some data, then now the time for run testing is begun. Please run following command to start Laravel server project.

php artisan serve

Launch you browser navigate to the URL http://localhost:8000

You might also like...

 

JQuery  Laravel  PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him