AutoSuggest with Laravel (v4.2)

- https://github.com/twitter/typeahead.js/
- https://laravel.com/docs/4.2

  • view/index.blade.php
{{ Form::open(['url' => '/profile', 'method' => 'get']) }}
  {{ Form::text('user', null, ['id'=>'users']) }}
  {{ Form::submit('GO') }}
{{ Form::close() }}
  • routes.php
Route::get('/', 'SearchController@index');
Route::get('/query', 'SearchController@query');
  • controllers/SearchController.php
public function index()
{
  return View::make('index');
}

public function query()
{
  $query = Input::get('user');
  $res   = User::where('username', 'LIKE', "%$query%")->get();
  return Response::json($res);
}
  • main.js
jQuery(document).ready(function($) {
  var engine = new Bloodhound({
    remote: '/query?user=%QUERY%',
    // '...' = displayKey: '...'
    datumTokenizer: Bloodhound.tokenizers.whitespace('username'),
    queryTokenizer: Bloodhound.tokenizers.whitespace
  });

  engine.initialize();

  $("#users").typeahead({
      hint: true,
      highlight: true,
      minLength: 2
  }, {
    source: engine.ttAdapter(),

    // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
    name: 'User_list',

    // the key from the array we want to display (name,id,email,etc...)
    displayKey: 'username',
    templates: {
      empty: [
        '<div class="empty-message">unable to find any</div>'
      ]
    }
  });
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s