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 class="empty-message">',
- '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 moduleYou 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 Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- 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 Illuminate\Database\Eloquent\Model;
- class Product extends Model
- {
- public $fillable = ['name','details'];
- }
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'));
Now create a AutoCompleteController.php
in following path app/Http/Controllers/AutoCompleteController.php add two functionality inAutoCompleteController
Controller
- 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);
- }
Create a master layout as Laravel standard.
- <!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 class="container">
- @if ($message = Session::get('success'))
- <div class="alert alert-success">
- <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) {
- return process(data);
- });
- }
- });
- </script>
- @endsection
You can also click this url to see the Manual Laravel Autocomplete search from Database