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.
- $('#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;
- });
$('#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.
- use IlluminateDatabaseSchemaBlueprint;
- use IlluminateDatabaseMigrationsMigration;
- class CreateProductsTable extends Migration
- {
- public functionup()
- {
- Schema::create('products',function(Blueprint $table){
- $table->increments('id');
- $table->string('name');
- $table->text('details');
- $table->timestamps();
- });
- }
- public functiondown()
- {
- Schema::drop("products");
- }
- }
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
- namespace App;
- use IlluminateDatabaseEloquentModel;
- class Product extends Model
- {
- public $fillable=['name','details'];
- }
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
- Route::get('typeahead-search',array('as'=>'typeahead.search','uses'=>'AutoCompleteController@sampleForm'));
- 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
- public functionsampleForm(){
- returnview('autocomplete');
- }
- public functiontypeahead(Request $request){
- $query=$request->get('term','');
- $products=Product::where('name','LIKE','%'.$query.'%')->get();
- returnresponse()->json($products);
- }
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.
- <!DOCTYPEhtml>
- <htmllang="en">
- <head>
- <metacharset="utf-8">
- <metahttp-equiv="X-UA-Compatible"content="IE=edge">
- <metaname="viewport"content="width=device-width, initial-scale=1">
- <title>Laravel Bootstrap Typeahead Autocomplete Search from Database</title>
- <linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"rel="stylesheet">
- <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
- <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
- </head>
- <body>
- <divclass="container">
- @if ($message = Session::get('success'))
- <divclass="alert alert-success">
- <p>{{ $message }}</p>
- </div>
- @endif
- @yield('content')
- </div>
- </body>
- </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
- @extends('layouts.master')
- @section('content')
- <div class="row">
- <div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3">
- <div class="panel panel-primary">
- <div class="panel-heading">Example of Bootstrap Typeahead Autocomplete Search Textbox</div>
- <div class="panel-body">
- <div class="form-group">
- {!! 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){
- returnprocess(data);
- });
- }
- });
- </script>
- @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
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