-
-
Save imranismail/10200241 to your computer and use it in GitHub Desktop.
//SearchController.php | |
public function autocomplete(){ | |
$term = Input::get('term'); | |
$results = array(); | |
$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 | |
{{ Form::open(['action' => ['SearchController@searchUser'], 'method' => 'GET']) }} | |
{{ Form::text('q', '', ['id' => 'q', 'placeholder' => 'Enter name'])}} | |
{{ Form::submit('Search', array('class' => 'button expand')) }} | |
{{ Form::close() }} | |
//Route | |
Route::get('search/autocomplete', 'SearchController@autocomplete'); | |
//Javascript | |
$(function() | |
{ | |
$( "#q" ).autocomplete({ | |
source: "search/autocomplete", | |
minLength: 3, | |
select: function(event, ui) { | |
$('#q').val(ui.item.value); | |
} | |
}); | |
}); |
Great script its working fine.
Style it with Bootstrap:
https://stackoverflow.com/questions/17838380/styling-jquery-ui-autocomplete
is very good and very easy.Thank!!! Please someone have one idea about implement a cache too in this code.
@gdbyte's code works perfectly, however, you need to change the SearchController.php code from:
return response()->json($term);
to:
return response()->json($result);
You'll also need to make sure you include jQuery UI in your project, otherwise, you'll get an error saying that the autocomplete function doesn't exist.
Hi, I know i'm late, But i'm doing the same thing and yes it works but man its slow. How do I return the results more faster
@non-entity9 , I am also trying to get @gdbytes code to work:
-created SearchController.php and added his code. Updated model and query
-added route
-added input to view
-not sure where to put the JS file. Where do you put that?
What else do I need to do to get this to work? Thx in advance
Other than plugin, it is also necessary to intetgrate some full text search functionality, like Elasticsearch? I think autocomplete search works well when Elasticsearch is configure in the Laravel model.
I noticed that your web page does not include the JS library from jQuery Ui's CSS and JS library.
Firstly, include the following libaries into your web pages:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- jQuery UI -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
Checkout this guide: https://www.tutsmake.com/laravel-jquery-ui-autocomplete-ajax-search-example/
@goodbytes-gb thxx a lot !
Just one thing: where (and how) do you add
I am a beginner at laravel