Share this:
FacebookTwitterRedditPinterestTumblrTelegramSkypeMessengerWhatsAppShare

In this guide, I’ll demonstrate how to implement an autocomplete search feature in a Laravel 11 application using Typeahead.js.

To begin, we’ll set up a new Laravel 11 project and execute migrations to establish a ‘users’ table in the database. Afterwards, we’ll populate this table with some dummy user data using Tinker. Next, we’ll craft a basic Blade template featuring an input field. Utilizing Typeahead.js, we’ll implement an autocomplete textbox and employ Ajax to fetch data from the database dynamically. Let’s dive into the example code below:

Step-by-Step Guide for Implementing Typeahead JS Autocomplete Search in Laravel 11:

  • Step 1: Install Laravel 11
  • Step 2: Add Dummy Users
  • Step 3: Create Controller
  • Step 4: Create Routes
  • Step 5: Create View File
  • Run Laravel App

So, let’s see the simple steps to complete this task.

Step 1: Install Laravel 11

This step is optional but recommended. If you haven’t already created the Laravel application, you can proceed by running the following command:

composer create-project laravel/laravel example-app

Step 2: Add Dummy Users

After setting up the users table, we’ll populate it with some dummy user data using Laravel’s Tinker factory. Let’s generate these dummy records with the following command:

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

Step 3: Create Controller

Now, it’s time to create a new controller named SearchController. This controller will consist of two methods: one to return a view response and another to handle AJAX requests, providing JSON responses. Please add the following content to the controller file:

app/Http/Controllers/SearchController.php

<?php
namespace App\Http\Controllers;

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

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

/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function autocomplete(Request $request): JsonResponse
{
$data = User::select("name")
->where('name', 'LIKE', '%'. $request->get('query'). '%')
->take(10)
->get();

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

Step 4: Create Routes

In this step, we’ll create routes for both the Datatables layout file and for fetching data. Open your “routes/web.php” file and add the following routes:

routes/web.php

<?php
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\SearchController;

Route::get('demo-search', [SearchController::class, 'index']);
Route::get('autocomplete', [SearchController::class, 'autocomplete'])->name('autocomplete');

Step 5: Create View File

In the final step, let’s create searchDemo.blade.php in the resources/views directory to define the layout and list all items. You can use the following code:

resources/views/searchDemo.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Search from Database - Laravel 11 - LaravelTuts.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.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">
<div class="card mt-5">
<h3 class="card-header p-3">Autocomplete Search from Database - Laravel 11 - LaravelTuts.com</h3>
<div class="card-body">

<form action="#" method="POST" enctype="multipart/form-data" class="mt-2">
@csrf

<input class="typeahead form-control" id="search" type="text">

<div class="mb-3 mt-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>

</form>
</div>
</div>

</div>

<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('#search').typeahead({
source: function (query, process) {
return $.get(path, {
query: query
}, function (data) {
return process(data);
});
}
});
</script>

</body>
</html>

Run Laravel App:

To run the Laravel application, navigate to your project directory in the terminal and execute the following command:

php artisan serve

After hitting enter, your Laravel app will start running locally. You can then access it in your web browser by navigating to the URL provided in the terminal, typically http://localhost:8000/demo-search

Conclusion:

In conclusion, this article has guided you through the process of implementing an autocomplete search feature in a Laravel 11 application using Typeahead.js.

We’ve covered essential steps such as setting up the Laravel project, adding dummy data, creating controllers and routes, crafting the view file, and finally running the application.

By following these steps, you can enhance user experience and streamline search functionality within your Laravel projects. Experiment with different configurations and adapt the code to suit your specific requirements.

Embrace the power of autocomplete search to provide users with a seamless and efficient browsing experience.

Happy coding!

Share this:
FacebookTwitterRedditPinterestTumblrTelegramSkypeMessengerWhatsAppShare

Categorized in: