onlinecode

Laravel Bootstrap Typeahead Autocomplete Search from Database – onlinecode

Laravel Bootstrap Typeahead Autocomplete Search from Database – onlinecode

In this post we will give you information about Laravel Bootstrap Typeahead Autocomplete Search from Database – onlinecode. Hear we will give you detail about Laravel Bootstrap Typeahead Autocomplete Search from Database – onlinecodeAnd how to use it also give you demo for it if it is necessary.

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 >',
  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. });
  $('#keyword').typeahead(null, {            name: 'query',            displayKey: 'value',            source: autosuggest.ttAdapter(),            templates: {                empty: [                    '<div >',                    'Unable to find any suggestion for your query',                    '</div>'                ].join('n'),                suggestion: Handlebars.compile('<div>@{{value}}<br><span>@{{data}}</div>')            }        }).on('typeahead:selected', function (obj, datum) {            window.location.href = datum.href;        });

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 IlluminateDatabaseSchemaBlueprint;
  2. use IlluminateDatabaseMigrationsMigration;
  3. class CreateProductsTable extends Migration
  4. {
  5. public functionup()
  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 functiondown()
  15. {
  16. Schema::drop("products");
  17. }
  18. }
use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateProductsTable extends Migration{    public function up()    {        Schema::create('products', function (Blueprint $table) {            $table->increments('id');            $table->string('name');            $table->text('details');            $table->timestamps();        });    }    public function down()    {        Schema::drop("products");    }}

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 IlluminateDatabaseEloquentModel;
  3. class Product extends Model
  4. {
  5. public $fillable=['name','details'];
  6. }
namespace App;use IlluminateDatabaseEloquentModel;class Product extends Model{    public $fillable = ['name','details'];}

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'));
Route::get('typeahead-search',array('as'=>'typeahead.search','uses'=>'AutoCompleteController@sampleForm'));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 functionsampleForm(){
  2. returnview('autocomplete');
  3. }
  4. public functiontypeahead(Request $request){
  5.     $query=$request->get('term','');        
  6. $products=Product::where('name','LIKE','%'.$query.'%')->get();     
  7. returnresponse()->json($products);
  8. }
public function sampleForm(){    return view('autocomplete'); }public function typeahead(Request $request){        $query = $request->get('term','');               $products=Product::where('name','LIKE','%'.$query.'%')->get();               return response()->json($products);}

Step 3: Create View

Create a master layout as Laravel standard.

  1. <!DOCTYPEhtml>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="utf-8">
  5. <metahttp-equiv="X-UA-Compatible"content="IE=edge">
  6. <metaname="viewport"content="width=device-width, initial-scale=1">
  7. <title>Laravel Bootstrap Typeahead Autocomplete Search from Database</title>
  8. <linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"rel="stylesheet">
  9. <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  10. <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
  11. </head>
  12. <body>
  13. <divclass="container">
  14. @if ($message = Session::get('success'))
  15. <divclass="alert alert-success">
  16. <p>{{ $message }}</p>
  17. </div>
  18. @endif
  19. @yield('content')
  20. </div>
  21. </body>
  22. </html>
<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel Bootstrap Typeahead Autocomplete Search from Database</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://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  </head><body><div >    @if ($message = Session::get('success'))        <div >            <p>{{ $message }}</p>        </div>    @endif        @yield('content')</div></body></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. returnprocess(data);
  21. });
  22. }
  23. });
  24. </script>
  25. @endsection
@extends('layouts.master')@section('content')   <div >        <div >            <div >              <div >Example of Bootstrap Typeahead Autocomplete Search Textbox</div>             <div >             <div >                                {!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}            </div>        </div>    </div></div></div><script type="text/javascript">    var url = "{{ route('typeahead.response') }}";    $('#search_text').typeahead({        source:  function (query, process) {        return $.get(url, { query: query }, function (data) {                return process(data);            });        }    });</script>@endsection

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

Show Demo

Label :

PHP

Laravel PHP Framework

jQuery

API

Bootstrap

JavaScript

Hope this code and post will helped you for implement Laravel Bootstrap Typeahead Autocomplete Search from Database – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version