Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
});
});
@alecz2303

This comment has been minimized.

Copy link

@alecz2303 alecz2303 commented Oct 15, 2014

Thanks man... this code is simple and easy to use...!!!

@jlcanizales

This comment has been minimized.

Copy link

@jlcanizales jlcanizales commented Nov 3, 2014

Great bro, Thanks!!

@rian-widianto

This comment has been minimized.

Copy link

@rian-widianto rian-widianto commented Feb 2, 2015

Simple and Nice, Thanks !!!

@maguichisss

This comment has been minimized.

Copy link

@maguichisss maguichisss commented Feb 9, 2015

I spent many hours trying to send the result correctly, you save my life!!! or hours at least :D

@annanatsir

This comment has been minimized.

Copy link

@annanatsir annanatsir commented Mar 2, 2015

i try that code. but it dosen't work...
when i run search/autocomplete, it shows my query[work]

@HashmatWaziri

This comment has been minimized.

Copy link

@HashmatWaziri HashmatWaziri commented Apr 13, 2015

@jackyliang

This comment has been minimized.

Copy link

@jackyliang jackyliang commented Jul 24, 2015

Thank you. This works perfectly.

@jocares

This comment has been minimized.

Copy link

@jocares jocares commented Aug 11, 2015

Thank you... :)

@subashbasnet8

This comment has been minimized.

Copy link

@subashbasnet8 subashbasnet8 commented Aug 23, 2015

this is great script :). Thanks

@chriz74x

This comment has been minimized.

Copy link

@chriz74x chriz74x commented Nov 11, 2015

Hello, you user SearchController@searchUser in your view, however you didn't define anything like that in the search controller, so ? I used this script in laravel 5.1 and it's not working at all.

@ramachandra-tawker

This comment has been minimized.

Copy link

@ramachandra-tawker ramachandra-tawker commented Nov 27, 2015

{{ Form::open(['action' => ['SearchController@searchUser'], 'method' => 'GET']) }}
{{ Form::text('q', '', ['id' => 'q', 'placeholder' => 'Enter name'])}}
{{ Form::submit('Search', array('class' => 'button expand')) }}
{{ Form::close() }}

this code doesn't display any text field or button but it displays the entire code as it is.

@asimshazad

This comment has been minimized.

Copy link

@asimshazad asimshazad commented Dec 30, 2015

Thanks you :)

@kuhakushiroe

This comment has been minimized.

Copy link

@kuhakushiroe kuhakushiroe commented Feb 19, 2016

@annanatsir
i try laravel 5.0.23
change source on javascript

source: "search/autocomplete",

to

source: "{{URL('search/autocomplete')}}",

@manoj-nandakumar

This comment has been minimized.

Copy link

@manoj-nandakumar manoj-nandakumar commented Feb 20, 2016

Very good script, I have written the updated version that would work with Laravel 5.2
Laravel 5.2 And JqueryUI's Autocomplete Plugin
[https://gist.github.com/manoj-nandakumar/11beb90916dfbdc6af7a]

@nouart

This comment has been minimized.

Copy link

@nouart nouart commented Feb 23, 2016

I use laravel 5.2 and jQuery ui 1.11.4 and dosn't work for me , please see the image below
you think what is the solution ?
autocomplete

@ChamandeepSingh

This comment has been minimized.

Copy link

@ChamandeepSingh ChamandeepSingh commented Feb 23, 2016

Please remove jQuery ui 1.11.4 from your code
and check ,its just confliction of jqueries

@nouart

This comment has been minimized.

Copy link

@nouart nouart commented Feb 23, 2016

I have removed jQuery ui 1.11.4 from the code but i have this error
Uncaught TypeError: $(...).autocomplete is not a function
But the title of autocomplete is : Laravel And JqueryUI's Autocomplete Plugin , it is used jquery ui

@ChamandeepSingh

This comment has been minimized.

Copy link

@ChamandeepSingh ChamandeepSingh commented Feb 24, 2016

You just need these two jqueries

jquery-1.9.1.min.js and (query-ui.js or ui 1.11.4.js)

@nouart

This comment has been minimized.

Copy link

@nouart nouart commented Feb 24, 2016

I have user only jquery-1.9.1.min.js and (query-ui.js or ui 1.11.4.js) but no solution for this problème , it is the same
this my index.blade.php

``` @extends('layouts.app')`

@section('content')

Dashboard
            </tbody>
        </table>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript"> /*$(document).ready(function(){ var route = "{{ URL('/employees') }}"; $.get(route, function(res){ $(res).each(function(key, value){ $('#data').append(""); }); }); });*/ </script> <script type="text/javascript" > $('document').ready(function(){ /* $('#search-input').attr('autocomplete', 'on');*/ $("#search-input").autocomplete({ source : '{{ URL('/api/employees') }}', minlength: 1, autoFocus: true, /* select: function(event,ui){ console.log("nouar"); $('#search-input').val(ui.item.value); $('#employee_N').val(ui.item.employee_N); $('#first_name').val(ui.item.first_name); $('#last_name').val(ui.item.last_name); $('#status').val(ui.item.status); }*/ }); }); </script>

@endsection

E. Number Firstname Lastname Title Direction Recruitment date Grade
"+value.employee_N+""+value.frst_name+""+value.last_name+""+value.title+""+value.direction+""+value.recruitment_date+""+value.grade+"
@ChamandeepSingh

This comment has been minimized.

Copy link

@ChamandeepSingh ChamandeepSingh commented Feb 25, 2016

Please use this code , this is your updated code and make sure your route and controller have no error

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

$('document').ready(function(){
/* $('#search-input').attr('autocomplete', 'on');*/
$("#search-input").autocomplete({
source : "{{ URL('/api/employees') }}",
minlength: 1,

       select: function(event,ui){

           $('#search-input').val(ui.item.value);

            }
    });

});

@ChamandeepSingh

This comment has been minimized.

Copy link

@ChamandeepSingh ChamandeepSingh commented Feb 25, 2016

with these changes its perfectly working for me

@manoj-nandakumar

This comment has been minimized.

Copy link

@manoj-nandakumar manoj-nandakumar commented Feb 28, 2016

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

This comment has been minimized.

Copy link

@esmeromichael esmeromichael commented Mar 12, 2016

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

This comment has been minimized.

Copy link

@WahabShah23 WahabShah23 commented May 12, 2016

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

This comment has been minimized.

Copy link

@masterk63 masterk63 commented Jul 13, 2016

Works perfectly!!!!!

@oncelot

This comment has been minimized.

Copy link

@oncelot oncelot commented Jul 21, 2016

perfect thanks

@yong0011

This comment has been minimized.

Copy link

@yong0011 yong0011 commented Jul 22, 2016

That's perfect script.
thanks

@fotouhifar

This comment has been minimized.

Copy link

@fotouhifar fotouhifar commented Jul 26, 2016

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

@a1iraxa

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@AselaG AselaG commented Sep 22, 2016

Thanks a lot !!!

@Gnaneshwar511

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@ddthanhdat ddthanhdat commented Oct 26, 2016

Thanks, it is verry helpfull

@tanvir-bd

This comment has been minimized.

Copy link

@tanvir-bd tanvir-bd commented Nov 5, 2016

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

This comment has been minimized.

Copy link

@clipvui2512 clipvui2512 commented Dec 4, 2016

great !!

@gassius

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@toto33331 toto33331 commented May 30, 2017

@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

This comment has been minimized.

Copy link

@Kiodaddy Kiodaddy commented Jun 14, 2017

Great script its working fine.

@emalgholzad

This comment has been minimized.

@zenen85

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@joshmeney joshmeney commented Feb 9, 2018

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

@CodeGirl300

This comment has been minimized.

Copy link

@CodeGirl300 CodeGirl300 commented Feb 21, 2018

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@azazqadir azazqadir commented Jul 24, 2019

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

This comment has been minimized.

Copy link

@Amr-F Amr-F commented Aug 24, 2020

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

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.