AppDividend
Latest Code Tutorials

Laravel Typeahead Search Tutorial With Example

1,768

Get real time updates directly on you device, subscribe now.

Laravel Typeahead Search Tutorial is the topic, we will discuss today. In a large web application, like an online market such as Amazon, Flipkart or social networking,  one of the most significant parts of the application is the search functionality. Having a great search feature will help your users find the right content(users, goods) instantly and efficiently. In this example, we are going to study, how to enhance your default search area in your site with real-time recommendations from the database. We will be using Laravel 5.6, jQuery and Typeahead to perform the smart search and Bootstrap for the styling. Typeahead.js is a flexible JavaScript library that gives strong support for building good search auto-completion.

When initializing a typeahead, there are some options you can configure. Some of them are:

  • highlight: Defaults to false
  • hint: Defaults to true
  • minLength: Defaults to 1

If you can get more information, then go to Github. So, let’s get started.

Laravel Typeahead Search Tutorial

We are going to Configure Laravel Project.

Step 1: Configure Laravel Project

Download new Laravel Project by the typing following command.

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

Step 2: Setup a MySQL database

Now, set the database in the .env file.

//.env

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

I have set up local database credentials.

Next, migrate two tables provided by Laravel Move to your terminal and pasted the following command.

php artisan migrate

It will raise two tables in your database.

  1. users
  2. password_resets  

Step 3: Compose a model and migration file

Type the following command in your cmd.

php artisan make:model SearchData -m

It will create two files.

  1. SearchData.php model.
  2. create__search_datas_table migration file.

We need to create Schema for the search data table. So navigate to Laravel  >>  database  >>  migrations  >>  create__search_datas_table.

// create_search_datas_table
public function up()
    {
        Schema::create('search_datas', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

In the database, you can see the search data table.

Step 4: Establish view file to add the data to the database

Create a file in resources  >>  views  >>   create.blade.php and put this following code in it.

<!-- create.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Typeahead Search 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 Typeahead Search 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">Name:</label>
            <input type="text" class="form-control" name="name">
          </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</button>
          </div>
        </div>
      </form>
   </div>
  </body>
</html>

Step 5: Create one controller and route 

php artisan make:controller SearchDataController --resource

It will create one controller file called SearchDataController.php

we register route in routes  >>  web.php file. So let us do it.

//web.php

Route::get('create','SearchDataController@create');
Route::post('store','SearchDataController@store');
Route::get('index','SearchDataController@index');
Route::get('search','SearchDataController@result');

Next step would be to go to SearchDataController.php file and add into create() function some code.

Related Posts
1 of 37
// SearchDataController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

After that, we want to begin Laravel Development server. Then follow the following command.

php artisan serve

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

Laravel Typeahead Search Example

Step 6: Save Data into Database

We need coding the store function in series to store the data in the database.

// SearchDataController.php

public function store(Request $request)
    {
        $data = new \App\SearchData();
        $data->name=$request->get('name');
        $data->save();
        return redirect('index')->with('success', 'Data has been added Please Now Search Over Here');
    }

You can see that we have added some data.

Laravel Bootstrap Typeahead Tutorial With Example

Step 7: Make an index page for Search the data

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

<!-- index.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel</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>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  </head>
  <body>
    <div class="container">
      <h2Laravel Typeahead Search Tutorial With Example></h2Laravel><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.

//SearchDataController.php

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

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

//SearchDataController.php

public function result(Request  $request)
    {
        $result=SearchData::where('name', 'LIKE', "%{$request->input('query')}%")->get();
        return response()->json($result);
    }

Final Code of SearchDataController.php looks like that

// SearchDataController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SearchDataController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }
    public function result(Request  $request)
    {
        $result=\App\SearchData::where('name', 'LIKE', "%{$request->input('query')}%")->get();
        return response()->json($result);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = new \App\SearchData();
        $data->name=$request->get('name');
        $data->save();
        return redirect('index')->with('success', 'Data has been added Please Now Search Over Here');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Step 7: Add jQuery in the View File

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

<!-- index.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) {
                return process(data);
            });
        }
    });
</script>

Final Code of index.blade.php looks like that

<!-- index.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel</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>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  </head>
  <body>
    <div class="container">
      @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) {
                return process(data);
            });
        }
    });
</script>
  </body>
</html>

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

Laravel Typeahead Search

Finally, Our Laravel Typeahead Search Tutorial With Example is over. Thanks for taking.

1 Comment
  1. Niket Pathak says

    Nice tutorial. As a side note, the version of typeahead used in this tutorial is not maintained since 3+ years now(reference github). There’s an actively maintained fork(as of 2018), here is their tutorial as well.

Leave A Reply

Your email address will not be published.

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