Created
February 20, 2016 09:35
-
-
Save manoj-nandakumar/11beb90916dfbdc6af7a to your computer and use it in GitHub Desktop.
Laravel 5.2 And JqueryUI's Autocomplete Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} | |
}); | |
}); |
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
you need the css
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
I have used the same example but i can't display data into the input box like fig
