Field Autocomplete Error - Laravel

Asked

Viewed 31 times

0

I’m having trouble implementing a autocomplete field, I’m used Laravel 5.9 and Bootstrap Typeahead JS.

Follows code:

Route:

Route::get('buscarservicos', 'SearchController@searchService')->name('searchService');

Controller:

public function searchService(Request $request)
{
    $data = DB::table('service')
            ->select('des_ser')
            ->where("des_ser","LIKE","%{$request->input('service')}%")
            ->get();
    //retorna uma json para tratar na view
    return response()->json($data);
}

View:

<div class="form-group">
       <label for="service">Serviço</label>
       <input class="typeahead form-control" type="text" 
        name="service" id="service">
</div>

<script type="text/javascript">
    var path = "{{ route('searchService') }}";
    $('input.typeahead').typeahead({
    source:  function (query, process) {
    return $.get(path, { query: query }, function (data) {
    return process(data);
    });
    }
    });
</script>

The search is performed, but when receiving the controller’s return, the system shows the following error:

bootstrap3-typeahead.min.js:1 Uncaught Typeerror: this.displayText(...). toLowerCase is not a Function

Anyone have any idea what might be causing the problem?

  • in return have to have a layout [{ id: 1, name: "texto" }, ...] in case your lack normalize this.

  • How could I accomplish that? Can you give me an example?

  • I made an example of your code!

1 answer

1


Needs a layout of return as follows:

[{id: 1, name: "texto"}, ... ]

then on the return of his method of controller such change in the method select of DB:

public function searchService(Request $request)
{
    $data = DB::table('service')
            ->select('des_id as id', 'des_ser as name')
            ->where("des_ser","LIKE","%{$request->input('service')}%")
            ->get();
    return response()->json($data);
}

therefore:

'des_id as id', 'des_ser as name'

to rename the fields to the layout (Observing: I don’t know if you have that field des_id mere assumption to exemplify, I believe this table has the identification field, so put the name)

  • 1

    Virgilio, that’s right. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.