Autocomplete text field in laravel using database

2020-06-21 04:31发布

问题:

I am trying to make a autocomplete form like below but the form do not show the suggestion as my database query is ok.

Form cole:

Controller method code:

Routes:

When I search on the link I get the query result like this:

Shows the result:

[{"id":1,"value":"sourav hossen"},{"id":2,"value":"sourav hossen"},{"id":3,"value":"sourav hossen"},{"id":4,"value":"a b"},{"id":5,"value":"a a"}]

回答1:

Try this change, some time will work.

source: "{{URL::route('autocomplete')}}",


回答2:

I tried to do it with jquery ajax and it worked.
First of all you should include a jquery library before the following code.

The javascript code in your view should be:

<script>
$(document).ready(function(){
    $('#q').keyup(function () {
        var q=$(this).val();
        if(word.length>3) {

            $.ajax
            ({
                type: "GET",
                url: "test2",
                data: {q:q},
                contentType: "json",
                cache: false,
                success: function(data, status, xhr)
                {
                    $('#q').val(data[0].value);
                }
            });
        }
    });

});
</script>

In your controller you should get the ajax data

public function autocomplete(Request $request)
{
    $input = $request->all();
    $term = $input['q'];
    $result = array();
    $queries = ...(do whatever you like)

                ->take(5)->get();
    foreach($queries as $query)
    {
        $result[] = ['id'=> $query->id,'value'=>$query->firstname.' '.$query->lastname];
    }

    return response()->json($result);

}

Try this and if you find any difficulty, i'll be here.