Create autocomplete from DB

Submitted by haruncpi - 11 months ago

This snippet will help you to make autocomplete from the database. You will get more instruction about it https://bit.ly/2rFmUEW

//in controller
public function getAutocompleteData(Request $request){
        if($request->has('term')){
            return Product::where('name','like','%'.$request->input('term').'%')->get();
        }
}

//JS part
$(function () {
   $('#product_id').autocomplete({
       source:function(request,response){
        
           $.getJSON('?term='+request.term,function(data){
                var array = $.map(data,function(row){
                    return {
                        value:row.id,
                        label:row.name,
                        name:row.name,
                        buy_rate:row.buy_rate,
                        sale_price:row.sale_price
                    }
                })

                response($.ui.autocomplete.filter(array,request.term));
           })
       },
       minLength:1,
       delay:500,
       select:function(event,ui){
       		//bind data in inputs like ui.item.name
       }
   })
})

//more detail: https://bit.ly/2rFmUEW