Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active April 4, 2024 13:15
Show Gist options
  • Save imranismail/10200241 to your computer and use it in GitHub Desktop.
Save imranismail/10200241 to your computer and use it in GitHub Desktop.
Laravel And JqueryUI's Autocomplete Plugin
//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);
}
});
});
@manoj-nandakumar
Copy link

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

@esmeromichael
Copy link

it's work but how can I get the id value after selecting data. I tried $('.').on('change', function()) but it doesn't work. What function I should use?

@WahabShah23
Copy link

I mean i am getting data like this

[{"id":176,"value":"MYKONOS AIRPORT(JMK) => CENTRAL MYKONOS"},{"id":180,"value":"MYKONOS AIRPORT(JMK) => CENTRAL MYKONOS"},{"id":588,"value":"KUSADASI => BODRUM"},{"id":589,"value":"BODRUM => KUSADASI"},{"id":596,"value":"KUSADASI => CESME"},{"id":597,"value":"CESME => KUSADASI"},{"id":598,"value":"KUSADASI => DIDIM"},{"id":610,"value":"KUSADASI => ANTALYA"},{"id":611,"value":"ANTALYA => KUSADASI"},{"id":612,"value":"KUSADASI => FETHIYE"},{"id":1194,"value":"KUSADASI => BODRUM"},

Although data is correct but ofcourse i want it when user searches for anything

@masterk63
Copy link

Works perfectly!!!!!

@oncelot
Copy link

oncelot commented Jul 21, 2016

perfect thanks

@yong0011
Copy link

That's perfect script.
thanks

@fotouhifar
Copy link

After one week I solve my problem with your nice and clean code. YOU ARE LEGEND! Thank you.

@a1iraxa
Copy link

a1iraxa commented Aug 2, 2016

How to send id in value not actual text.
Even i have updated this:
$('#customer_name').val(ui.item.value);
to
$('#customer_name').val(ui.item.id);
but still posting value instead customer id.

html:
<input type="text" class="form-control" id="customer_name" name="customer_name" placeholder="Enter name">

Please help me.

@AselaG
Copy link

AselaG commented Sep 22, 2016

Thanks a lot !!!

@Gnaneshwar511
Copy link

Gnaneshwar511 commented Sep 26, 2016

In Laravel 5.2
$term = Request::get('q'); is working.
use Request;
and if you want to use 'Illuminate\Http\Request' (Request Object) then type the line use Illuminate\Http\Request; and write
public function autoComplete(Request $request){ $term = $request->get('q');

@ddthanhdat
Copy link

Thanks, it is verry helpfull

@tanvir-bd
Copy link

I am using Laravel 5.2 and have done as per above. When I type something in text box it shows all result set not the particular result. Could you please help in this regard ?

@clipvui2512
Copy link

great !!

@gassius
Copy link

gassius commented Feb 22, 2017

I am trying to make this work on Laravel 5.4 basic differences with the original is using Request instead of Input and response()->json($results) intead of Response::json

My text field send the request to the route and I got a 200 response (and if a see it on the browser is correct), but I am getting this error on the console:
TypeError: elem.getClientRects is not a function

And is not displaying the options.

Please advice

EDIT: That error was coming from using jquery-ui-bundle (because somehow jquery-ui is not Mix friendly) and bundle is stuck on 1.11.x and that won't work with jquery 3.x. Solved by placing jquery-ui manually on resources.

Now all seems to work, except there is not displaying of options whatsoever

@mforcer
Copy link

mforcer commented Feb 28, 2017

@gassius This code can actually be simplified quite a bit, here is my implementation with Laravel 5.4. No need for foreach looping through the data.

SearchController.php:

public function autocomplete()
{
	$term = request('term');
        $result = Model::whereName($term)->orWhere('name', 'LIKE', '%' . $term . '%')->get(['id', 'name as value']);
        return response()->json($term);
}

Model and query should be adjusted to search the data source you require, plus a limit with take() if required.

You should also avoid hardcoding the source URL. It can be done like this:

routes/web.php:

Route::get('search/autocomplete', ['as' => 'search-autocomplete', 'uses' => 'SearchController@autocomplete']);

view:

<input type="text" name="term" id="q" data-action="{{ route('search-autocomplete') }}">

We're referencing the action with the route() helper in a data-action attribute, this can now be passed through to the JS file like so:

$('#q').each(function() {
        var $this = $(this);
        var src = $this.data('action');

        $this.autocomplete({
            source: src,
            minLength: 2,
            select: function(event, ui) {
                $this.val(ui.item.value);
                $('#id').val(ui.item.id);
            }
        });
    });

source is assigned the route from data-action, which is defined in our routes file. No need for hard coding urls.

Bonus. I've added a hidden field to the form to capture the ID of the selection

{!! Form::hidden('source_id', ['class' => 'source_id', 'id' => 'source_id']) !!}

source_id should obviously reflect the column name.

Hope this helps

@toto33331
Copy link

@goodbytes-gb thxx a lot !
Just one thing: where (and how) do you add

{!! Form::hidden('source_id', ['class' => 'source_id', 'id' => 'source_id']) !!}

I am a beginner at laravel

@Kiodaddy
Copy link

Great script its working fine.

@emalgholzad
Copy link

@zenen85
Copy link

zenen85 commented Nov 18, 2017

is very good and very easy.Thank!!! Please someone have one idea about implement a cache too in this code.

@joshmeney
Copy link

@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.

@stephanycode
Copy link

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

@P373
Copy link

P373 commented May 25, 2018

@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

@azazqadir
Copy link

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.

@Amr-F
Copy link

Amr-F commented Aug 24, 2020

Screenshot (140)
Uncaught TypeError: $(...).autocomplete is not a function .........any solutions ?

@tutsmake
Copy link

tutsmake commented Apr 4, 2024

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/

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