Twitter Typeahead integration in Laravel
In this post we will show you Twitter Typeahead integration in Laravel, hear for Twitter Typeahead integration in Laravel we will give you demo and example for implement.
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
Hope this code and post will helped you for implement Twitter Typeahead integration in Laravel. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs us
Comments
Post a Comment