Twitter Typeahead integration in Laravel


The twitter typeahead is one of the most famous fully featured ajax driven live search plugin available completely free right now. Another alternative to this plugin is Jquery UI Autocomplete. In this tutorial, I will show you the easiest way to integrate typeahead.js  version 0.9.3 in your Laravel project. The search box will fetch data remotely using ajax.

The Javascript Code is given below

<!-- Typeahead -->
{!! Html::script('js/typeahead.min.js') !!}
<script>
$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote:"{{ url('/search/%QUERY') }}",
        limit : 5,
    });        
});
</script>

The code for material design lite search box (You can demo it on the navigation bar of this site) is given below

                <div style="padding-bottom:0px;" class="mdl-textfield mdl-js-textfield mdl-textfield--expandable">
                    <label class="mdl-button mdl-js-button mdl-button--icon" for="search-expandable">
                      <i class="material-icons">search</i>
                    </label>
                    <div class="mdl-textfield__expandable-holder">
                        <input class="mdl-textfield__input typeahead" type="text" name="search" id="search-expandable" style="width: 300px;">
                      <label class="mdl-textfield__label" for="search-expandable"></label>
                    </div>
                </div>

Now it is time to setup routes in laravel

Route::get('search/{key}','HomeController@getSearch')
       ->where('key','^[\w\d\-\_\. ]+$');

Now the getSearch function code in HomeController

public function getSearch($key)
{
    $posts = Post::where('title', 'like', '%' . $key . '%')->limit(5)->get();
        
    foreach($posts as $post)
    {
        $array[] = $post->title;
    }
        
    return json_encode($array);      
}

Final step some CSS to improve the looks

<style>
.tt-hint {
  color: #7c4dff; }

.tt-dropdown-menu {
  background-color: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  margin-top: 12px;
  padding: 8px 0;
  width: 300px; }

.tt-suggestion {
  padding: 3px 20px; }

.tt-suggestion.tt-is-under-cursor {
  background-color: #7c4dff;
  color: #FFFFFF; }

.tt-suggestion p {
  margin: 0; }
</style>

Note

     I use an old version of typeahead because it is much stable and easy to integrate than current version which is 11.1. If you are using latest version both code and CSS will not work as I design CSS for version 0.9.3. You can download the Typeahead version 0.9.3 from GitHub from the following link 

https://github.com/twitter/typeahead.js/releases/tag/v0.9.3 .


Web development
22nd Jul 2018 02:05:42 AM
PHP Laravel Javascript jQuery Ajax
5462

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.