Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :
InvestmentNovel

Latest Programming Tutorial Blog

Laravel Autocomplete Search From Database Using Typeahead Tutorial Example

/
/
/
117 Views

Laravel Autocomplete Search From Database Using Typeahead Tutorial Example is the topic, we will discuss today. We will be using Laravel 5.7, jQuery and Typeahead to perform a smart search and Bootstrap for the styling. In a huge web application, like an online market such as Flipkart, Amazon or social networking,  one of the important parts of the application is the search functionality.  Having a fabulous search feature will help your users find the right product instantly and efficiently.

Laravel Autocomplete Search From Database Using Typeahead Tutorial Example

We are going to Configure Laravel Project.

#1: Install Laravel 5.7 Project

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

#2: Configure SQL Database

Now we can setup database credentials.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelautocompletesearch
DB_USERNAME=root
DB_PASSWORD=

#3: Compose a Model and Migration File

Type following command in your cmd.

php artisan make:model Product -m                                             

It will create the product.php file and also create a create_products_table.php  migration file.

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('productname');
            $table->timestamps();
        });
    }

In the database, you can see the product table.

Now, migrate table by the following command.

php artisan migrate

#4: Create a View File

You can create a file in resources/views/createproduct.blade.php and put this following code in it.

<!-- createproduct.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Autocomplete Search From Database Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2>Laravel Autocomplete Search From Database Tutorial With Example</h2><br/>
      <form method="post" action="{{url('store')}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Name">Product Name:</label>
            <input type="text" class="form-control" name="productname">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Add Product</button>
          </div>
        </div>
      </form>
   </div>
  </body>
</html>

#5: Create one controller

php artisan make:controller ProductController

It will build the controller file called ProductController.php.

//ProductController.php

public function create()
    {
        return view('createproduct');
    }

#6: Define Route

We register all route in a web.php file

//web.php

Route::get('createproduct','ProductController@create');
Route::post('store','ProductController@store');
Route::get('createproduct/index','ProductController@index');
Route::get('search','ProductController@result');

we want to start ravel Development server.

php artisan serve

Move to the browser and hit the URL: http://localhost:8000/createproduct

Laravel Autocomplete Search From Database Using Typeahead Tutorial

#7: Save data to the database

We want to code the store()  in sequence to store the data in the database.

//ProductController.php

public function store(Request $request)
    {
        $product = new \App\Product();
        $product->productname=$request->get('productname');
        $product->save();
        return redirect('createproduct/index')->with('success', 'Data has been added Successfully');
    }

You can see that we have added some data.

Laravel Autocomplete Search From Database Using Typeahead Example

#8: Create an index page for Search the data

In resources/views produce specific blade file called indexproduct.blade.php file and set the subsequent code in it.

<!-- indexproduct.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.7</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script></head>
  <body>
    <div class="container">
      <h2>Laravel 5.7 Autocomplete Search From Database Tutorial With Example</h2><br/>
      @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Search">Search:</label>
            <input type="text" class="form-control" id="search" name="search">
          </div>
        </div>
    </div>
  </body>
</html>

Add into index() function some code.

//ProductController.php

public function index()
    {
        return view('indexproduct');
    }

Next, we want to write a query in Controller and return data to view file so write below code into the controller file.

//ProductController.php

public function result(Request  $request)
    {
        $result=\App\Product::select('productname')->where('productname', 'LIKE', "%{$request->input('query')}%")->get();
        return response()->json($result);
    }

Final Code of ProductController.php looks like that.

//ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function create()
    {
        return view('createproduct');
    }
    public function store(Request $request)
    {
        $product = new \App\Product();
        $product->productname=$request->get('productname');
        $product->save();
        return redirect('createproduct/index')->with('success', 'Data has been added Successfully');
    }
    public function index()
    {
        return view('indexproduct');
    }
    public function result(Request  $request)
    {

        $result=\App\Product::select('productname')->where('productname', 'LIKE', "%{$request->input('query')}%")->get();
        return response()->json($result);
    }
}

#9: Add jQuery in the Index File

Include some code into the indexproduct.blade.php file.

<!-- indexproduct.blade.php -->

<script type="text/javascript">


    var path = "{{ url('search') }}";

    $('#search').typeahead({
         minLength: 2,
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
            var dataset = [];
                data.forEach(function(value){
                    dataset.push(value.productname);
                });
                return process(dataset);
            });
        }
    });
    </script>

Final Code of indexproduct.blade.php looks like that

<!-- indexproduct.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel 5.7</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script></head>
  <body>
    <div class="container">
      <h2>Laravel 5.7 Autocomplete Search From Database Tutorial With Example</h2><br/>
      @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Search">Search:</label>
            <input type="text" class="form-control" id="search" name="search">
          </div>
        </div>
    </div>
    <script type="text/javascript">


    var path = "{{ url('search') }}";

    $('#search').typeahead({
         minLength: 2,
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
            var dataset = [];
                data.forEach(function(value){
                    dataset.push(value.productname);
                });
                return process(dataset);
            });
        }
    });
    </script>
  </body>
</html>

You can see that we type Mo and suggestion are there.

Laravel Autocomplete Search From Database Tutorial Example

Finally, Our Laravel Autocomplete Search From Database Using Typeahead Tutorial Example is over. Thanks for taking.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This div height required for enabling the sticky sidebar