Sunday, June 26, 2016

Autocomplete search with Laravel | Laravel Autocomplete with jQuery UI

autocomplete search
Let's build a Autocomplete Search with Laravel and jQuery UI. Just do the following steps:

1. Let's create a Route first:

 Route::get('/autocomplete',[
  'uses'=>'UserController@autocomplete',
  'as'=>'autocomplete'
  ]);
2. Now Let's define the controller:

public function autocomplete(Request $request)
    {
          $term = $request->term;
          $results=array();
          $queries = DB::table('users')
                         ->where('name', 'LIKE', '%'.$term.'%')
                         ->take(5)->get();
      
          foreach ($queries as $data) 
              {
                    $results[]=['id'=>$data->id,'value'=>$data->name];
              }
        return response()->json($results);
    }

3. Here comes the view page:


    (a)  Don't forget to put following cdn inside  of your  <head></head> tag first:

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
 <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> 
  <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
     (b) Now in body tag, first we have to make  a form where we'll put the key for searching and then add a JavaScript code just before the end body tag (</body>). Eg:

<div class="ui-widget"> 
    <input type="text" id="searchname" placeholder="Enter name" class="form-control"/>   
  </div> 
   <script type="text/javascript">
           jQuery(document).ready(function($) {
                 $('#searchname').autocomplete({
                       source: "{{ route('autocomplete') }}" ,
                       minlength:1,
                       autofocus:true,
                select:function(event,ui){
                     $("searchname").val(ui.item.value);
                   }
             });
       });
 </script>

  So That's it, when you visit the route in your url, you'll see like a  following autocomplete search in your view page.

autocomplete search demo



Thank you for reading the full article.
 






















Related Articles

0 comments:

Post a Comment