Skip to content

Instantly share code, notes, and snippets.

@manoj-nandakumar
Created February 20, 2016 09:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manoj-nandakumar/11beb90916dfbdc6af7a to your computer and use it in GitHub Desktop.
Save manoj-nandakumar/11beb90916dfbdc6af7a to your computer and use it in GitHub Desktop.
Laravel 5.2 And JqueryUI's Autocomplete Plugin
//SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Auth;
use DB;
use Response;
class SearchController extends Controller
{
public function autocomplete(){
$term = Input::get('term');
$results = array();
// this will query the users table matching the first name or last name.
// modify this accordingly as per your requirements
$queries = DB::table('users')
->where('first_name', 'LIKE', '%'.$term.'%')
->orWhere('last_name', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->first_name.' '.$query->last_name ];
}
return Response::json($results);
}
}
// View
// If you would like to use the form facade, then please insstall it before
// https://laravelcollective.com/docs/5.0/html
{{ Form::open(['action' => ['SearchController@autocomplete'], 'method' => 'GET']) }}
{{ Form::text('q', '', ['id' => 'q', 'placeholder' => 'Search users'])}}
{{ Form::submit('Search', array('class' => 'btn btn-default')) }}
{{ Form::close() }}
Alternatively you can simply just use the HTML if you dont want the above method using form facade
<form method="GET" action="{{ url('search/autocomplete') }}">
<input id="q" placeholder="Search users" name="q" type="text" value="">
<input class="btn btn-default" type="submit" value="Search">
</form>
//Route
Route::get('search/autocomplete', 'SearchController@autocomplete');
//Javascript
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
$(function()
{
$( "#q" ).autocomplete({
source: "{{ url('search/autocomplete') }}",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
@nouart
Copy link

nouart commented Feb 23, 2016

I have used the same example but i can't display data into the input box like fig
autocomplete

@manoj-nandakumar
Copy link
Author

Please take a look at select2 it will get the job easier for you, if u need more help just let me know
https://select2.github.io/examples.html

@apysais
Copy link

apysais commented Nov 9, 2016

you need the css

@Gnaneshwar511
Copy link

Use
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment