Manual Laravel Autocomplete search from Database
Sometime we need autocomplete searchable text box which is reflect from database and we use third party plugins.Now I am going to tell you how to create manually autocomplete search text box in Laravel 5.2.
There should be installed Laravel 5.2 in your system if Laravel is not installed then install Laravel with following command.
composer create-project --prefer-dist laravel/laravel blogCreate a Products Table and Model
Follow below url till product table creation process or you can create `Products` table in your database and relatively create model in following path app/Product.php
with name `Product`.
Insert some test data in your product table or you can use Laravel seed classes to seeding your database with test data.If you want to write seeders then run this command that generate seed file in database/seeds
directory.
php artisan make:seeder UsersTableSeeder
Now let's start to creating autocomplete search text box.
Add Route and ControllerAdd these two routes in your routes.php
file.
- Route::get('autocomplete',array('as'=>'autocomplete','uses'=>'AutoCompleteController@index'));
- Route::get('searchajax',array('as'=>'searchajax','uses'=>'AutoCompleteController@autoComplete'));
Now we will create AutoCompleteController.php
in following path app/Http/Controllers
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Http\Controllers\Controller;
- use App\Product;
- class AutoCompleteController extends Controller {
- public function index(){
- return view('autocomplete.index');
- }
- public function autoComplete(Request $request) {
- $query = $request->get('term','');
- $products=Product::where('name','LIKE','%'.$query.'%')->get();
- $data=array();
- foreach ($products as $product) {
- $data[]=array('value'=>$product->name,'id'=>$product->id);
- }
- if(count($data))
- return $data;
- else
- return ['value'=>'No Result Found','id'=>''];
- }
- }
Now we will create index.blade.php
file in following resources/views/autocomplete/ directory.
- @extends('layouts.default')
- @section('content')
- <div class="row">
- <div class="col-xs-12 col-sm-12 col-md-12">
- <div class="form-group">
- {!! Form::text('search_text', null, array('placeholder' => 'Search Text','class' => 'form-control','id'=>'search_text')) !!}
- </div>
- </div>
- </div>
- <script>
- $(document).ready(function() {
- src = "{{ route('searchajax') }}";
- $("#search_text").autocomplete({
- source: function(request, response) {
- $.ajax({
- url: src,
- dataType: "json",
- data: {
- term : request.term
- },
- success: function(data) {
- response(data);
- }
- });
- },
- minLength: 3,
- });
- });
- </script>
- @endsection
- <link href="http://demo.expertphp.in/css/jquery.ui.autocomplete.css" rel="stylesheet">
- <script src="http://demo.expertphp.in/js/jquery.js"></script>
- <script src="http://demo.expertphp.in/js/jquery-ui.min.js"></script>