Autocomplete Ajax Search in Laravel 9 Using Typehead

This tutorial covers the implementation of autocomplete Ajax search in Laravel 9 using typehead JS which is a javascript library that is mostly used in the suggestion system and here we are also suggesting some search inputs to the user upon entering just an alphabet in the search box.

We will dive through the example step by step. Firstly we will create a new project and then we will create a model, factory, and migration for the posts table, and then we will create the controller and blade files to write the backend and frontend logic for the example respectively.

So let’s start with step 1…

Step 1: Install Laravel 9 project

In this first step, we will install the laravel Application with the name “AutocompeleteSearch”.

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

Step 2: Creating migration, factory, and model 

Now to create a migration, factory, and model for the students, let’s run the following command in the terminal.

php artisan make:model Post -mf

This command will create a migration as, a factory and a model for students. here we are generating a factory that will help us inject dummy student’s data into the database which we will do in step 3. let’s navigate these files in their respective directories and write the code.

/database/migrations/2021_05_27_100722_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('Description');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Now we need to run the migration using the following command:

php artisan migrate

 /Database/Factories/PostFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name(),
            'description' => $this->faker->name(),
            

        ];
    }
}

/App/Models/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Write code on Method
     *
     * @return response()
     */
     protected $fillable = [
        'name', 'description',
    ];
}

Step 3: Injecting dummy students

We will inject dummy data using the PHP tinker command.

php artisan tinker
  
Post::factory()->count(20)->create()

Step 4: Creating routs

now we will create two routes, one for indexing the page and the other to process ajax requests for searching in the database asynchronously.

<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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('/', [PostController::class, 'index']);
Route::get('/typeHeadSearch', [PostController::class, 'typeHeadSearch'])->name('typeHeadSearch');

Step 4: Create Controller

In this step we will create StudentController using the command below:

php artisan make:controller <code class="language-php">PostController

Now in this controller, we will create 2 methods:

  • index()
  • typeHeadSearch()

 app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
      
        return view('welcome');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function typeHeadSearch(Request $request)
    {


        $searchData = User::select("name as value", "id")
        ->where('name', 'LIKE', '%'. $request->get('search'). '%')
        ->get();

        return response()->json($searchData);
    }
}

 

Step 5:Create Blade File

In this final step, we will create a welcome.blade.php to the right code for the search frontend.
/resources/views/index.blade.php
<!DOCTYPE html>
<html>
    <head>
        <title>>Laravel 9 Typehead JS autocompelete search - Laramatic.com</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/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 mt-4">
        <div class="row">
          <div class="col-md-10 mx-auto">
            <div class="card">
              <div class="card-header bg-primary text-white text-center">
                <h4>Laravel 9 Typehead JS autocompelete search - Laramatic.com</h4>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-12">
                    <input class="typehead form-control" id="search" type="text">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <script type="text/javascript">
        var path = "{{ route('typeHeadSearch') }}";

        $('#search').typeahead({
                source: function (query, process) {
                    return $.get(path, {
                        query: query
                    }, function (data) {
                        return process(data);
                    });
                }
            });

    </script>

</body>
</html>

Finally, we are ready to run our app and see the results, so run the following command:

php artisan serve

Let’s open the below URL in the browser and see the results.

http://localhost:8000

Output:

We hope that you learned about creating autocomplete search using typehead JS in laravel 9.