Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.