Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active April 4, 2024 13:15
Show Gist options
  • Star 86 You must be signed in to star a gist
  • Fork 40 You must be signed in to fork a gist
  • 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);
}
});
});
@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