Laravel autocomplete search box using typeahead and ajax

Laravel autocomplete search box using typeahead and ajax

Today, i am going to share an article to create laravel autocomplete search box using bootstrap typeahead and ajax. Here we will create a demo of autocomplete search bar. Autocomplete or autosuggestion search provides a easy way to search anything on the website.

A user who visit a website attracts from the amazing features which are very easy to use. And autoccomplete is also that type of feature. Typeahead provides this feature to integrate it in your web application.

We can also use only simple Jquery and ajax to create autocomplete search box. But it would not be very easy and compact like typeagead js. So let’s see the example of autocomplete search box using typeahead js and bootstrap in laravel. And jquery library would be must for this implementation. 

Here, we will create a demo of autocomplete search box from scratch means from installation of laravel to the complete working feature. So let’s follow step by step implementation process.

Step 1: Install Laravel

In the first step, let’s install a fresh laravel application using the composer command. So open your terminal or command prompt and execute the command as mentioned below.

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

after installing the laravel application, we will need to give the permission to this application to write logs and caches using the given command.

sudo chmod -R 777 /var/www/html/demo-project/storage

/var/www/html/demo-project is basically path of the application where it is installed. Please replace it from your own application folder’s path.

Step 2: Create Migration and Model

Now for creating migration file, open your terminal and run the following php artisan command.

php artisan make:migration create_products_table

After running the above artisan command there would be migration file created under database/migration directory. So open this products migration file and update the code like below to create products table structure.

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description')
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Now we will migrate this newly created migration using the php artisan command below.

php artisan migrate

After creating table, we will need to create a model for this products table. So let’s create a model file Product.php under app directoryor use the artisan command like below to create model.

php artisan make:model Product

Now, this model file will look like the code given below.

app/Product.php

<?php
  
namespace App;
   
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
       
}

Step 3: Add Route

In this third step we will create required routes to create this autocomplete feature. So open routes/web.php file and add the routes as given below.

routes/web.php

Route::get('search', 'ProductController@index')->name('search');
Route::get('autocomplete', 'ProductController@autocomplete')->name('autocomplete');

Step 4: Create Controller

As written in route, we have used ProductController for search logic. So now, we will create ProductController.php file under app/Http/Controllers and will add two methods index() and autocomplete() as mentioned in the route file. After creating this file add the following code into this controller file.

app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Product;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('search');
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(Request $request)
    {
        $data = Product::select("name")
                ->where("name","LIKE","%{$request->input('query')}%")
                ->get();
   
        return response()->json($data);
    }
}

Step 5: Create View File

After creating controller, we will need to create view file which is basically a blade file. It is also mentioned in the controller’s index() method above. And add the code in this view file as written below

resources/views/search.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel autocomplete search box using typeahead and ajax</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <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 autocomplete search box using typeahead and ajax</h1>   
    <input class="typeahead form-control" type="text">
</div>
   
<script type="text/javascript">
    var path = "{{ route('autocomplete') }}";
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
                return process(data);
            });
        }
    });
</script>
   
</body>
</html>

Step 6: Run this application

We have completed laravel autocomplete search box using typeahead and ajax. Since we have created this as a new application, so we will need to run this application. Here for development purpose you can run the following command to run this application on a port.

php artisan serve

After running the above command, you can check it in browser by opening the url as given below.

http://localhost:8000/search

You can also read the tutorial to create dependent country, state and city dropdown by clicking on the link below.

Laravel dependent country state city dropdown ajax jquery