Laravel Bootstrap Typeahead Autocomplete Search from Database

Laravel Bootstrap Typeahead Autocomplete Search from Database

Laravel Bootstrap Typeahead Autocomplete Search from Database

Autocomplete make more flexible to get relevant data from database and i use different different type of autocomplete to search data from database.

I have already post article regarding manual autocomplete search from database but now i am going to use typeahead js to search data from database.

You can define custom template too in typeahead autocomplete search text box.

Here is a sample example to define template in searchable textbox if you are getting empty records from server api.

  1. $('#keyword').typeahead(null, {
  2. name: 'query',
  3. displayKey: 'value',
  4. source: autosuggest.ttAdapter(),
  5. templates: {
  6. empty: [
  7. '<div class="empty-message">',
  8. 'Unable to find any suggestion for your query',
  9. '</div>'
  10. ].join('\n'),
  11. suggestion: Handlebars.compile('<div>@{{value}}<br><span>@{{data}}</div>')
  12. }
  13. }).on('typeahead:selected', function (obj, datum) {
  14. window.location.href = datum.href;
  15. });

Now i am going to tell you step by step process to create typeahead autocomplete search box in Laravel.

Step 1: Create Products table and module

You should have a table with some demo data to text this code so first create a product table by creating migration file for products table using Laravel 5 php artisan comand.

php artisan make:migration create_products_table 

After this command you will get a migration file in following path database/migrations and now add below line of code in your migration file for create products table.

  1. use Illuminate\Database\Schema\Blueprint;
  2. use Illuminate\Database\Migrations\Migration;
  3. class CreateProductsTable extends Migration
  4. {
  5. public function up()
  6. {
  7. Schema::create('products', function (Blueprint $table) {
  8. $table->increments('id');
  9. $table->string('name');
  10. $table->text('details');
  11. $table->timestamps();
  12. });
  13. }
  14. public function down()
  15. {
  16. Schema::drop("products");
  17. }
  18. }

When you will run this command then you will find a table Products in your database.

Now you can feed demo data manually or you can use Laravel seed classes to seeding your database with test data.

Now create a Model for Product Table in following path app/Product.php

  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class Product extends Model
  4. {
  5. public $fillable = ['name','details'];
  6. }
Step 2: Add Route and Controller functionality

Add two routes for getting view form and second routes to getting database json response.

app/Http/routes.php

  1. Route::get('typeahead-search',array('as'=>'typeahead.search','uses'=>'AutoCompleteController@sampleForm'));
  2. Route::get('typeahead-response',array('as'=>'typeahead.response','uses'=>'AutoCompleteController@typeahead'));

Now create a AutoCompleteController.php in following path app/Http/Controllers/AutoCompleteController.php add two functionality inAutoCompleteController Controller

  1. public function sampleForm(){
  2. return view('autocomplete');
  3. }
  4. public function typeahead(Request $request){
  5.     $query = $request->get('term','');        
  6. $products=Product::where('name','LIKE','%'.$query.'%')->get();     
  7. return response()->json($products);
  8. }
Step 3: Create View

Create a master layout as Laravel standard.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Laravel Bootstrap Typeahead Autocomplete Search from Database</title>
  8. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
  9. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
  11. </head>
  12. <body>
  13. <div class="container">
  14. @if ($message = Session::get('success'))
  15. <div class="alert alert-success">
  16. <p>{{ $message }}</p>
  17. </div>
  18. @endif
  19. @yield('content')
  20. </div>
  21. </body>
  22. </html>

Now create a blade file in following path resources/views/autocomplete.blade.php

resources/views/autocomplete.blade.php
  1. @extends('layouts.master')
  2. @section('content')
  3. <div class="row">
  4. <div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3">
  5. <div class="panel panel-primary">
  6. <div class="panel-heading">Example of Bootstrap Typeahead Autocomplete Search Textbox</div>
  7. <div class="panel-body">
  8. <div class="form-group">
  9. {!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. </div>
  15. <script type="text/javascript">
  16. var url = "{{ route('typeahead.response') }}";
  17. $('#search_text').typeahead({
  18. source: function (query, process) {
  19. return $.get(url, { query: query }, function (data) {
  20. return process(data);
  21. });
  22. }
  23. });
  24. </script>
  25. @endsection

You can also click this url to see the Manual Laravel Autocomplete search from Database

Phone: (+91) 8800417876
Noida, 201301