Skip to content

Instantly share code, notes, and snippets.

@jandante
Created October 14, 2015 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jandante/ba577a007995e9d1139f to your computer and use it in GitHub Desktop.
Save jandante/ba577a007995e9d1139f to your computer and use it in GitHub Desktop.
Typeahead.js & Laravel
  • 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>'
			]
		}
	});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment