Laravel

Laravel Autocomplete Search Using Typeahead JS.

Autocomplete is a user-friendly way to display a large list of data on a page. It shows suggestions based on the input and a user can select an option from the list.

Ajax Autocomplete is must if you are dealing with big data table, like you have items or products table and thousands of records so it’s not possible to give drop-down box, but it is better if we use Autocomplete instead of select box.

In this example we will use Bootstrap Typeahead JS plugin for auto-complete, Typeahead.js plugin provide good layout using bootstrap so it pretty good. You can implement autocomplete in your laravel application just following few step.

Step 1 : Add Below Route.
Route::get('search', 'ProductController@index')->name('search');
Route::get('autocomplete', 'ProductController@autocomplete')->name('autocomplete');
Step 2 : Create Model And Add Below Code.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class product extends Model
{
    
}

Step 3 : Create Contorller And Add Below Code.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    //
    public function index(){

        return view('search');
    }

    public function autocomplete(Request $request){

        $datas = Product::where('name','LIKE','%'.
                              $request->input('query').'%')->get();
        return response()->json($datas);
    }
}
 
Step 4 : Create View And Add Below Code.
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Autocomplete Search Using Bootstrap Typeahead JS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.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">
        <div class="container">
           <h4 class="text-success">Autocomplete Search Using Bootstrap Typeahead JS</h4>
           <div class="panel panel-primary">
              <div class="panel-heading">Autocomplete Search Using Bootstrap Typeahead JS</div>
              <div class="panel-body">
                 <div class="form-group">
                    <input class="typeahead form-control" type="text">
                 </div>
              </div>
           </div>
        </div>
     </div>
 
<script type="text/javascript">
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('{{ route('autocomplete') }}', { query: query }, function (data) {       
                    return process(data);                
            });
        }
    });
</script>
</body>
</html>

Related Articles

Leave a Reply

Check Also
Close
Back to top button