I’m trying to get data for autocomplete using laravel.
Controller:
public function collection_search(Request $request) {
$term = $request->search;
$serveurapObj = new Serveurap();
$result = $serveurapObj->collectionAutocomplete();
return response()->json($result);
}
Model:
public function collectionAutocomplete($term) {
$where= ['m.supprime'=>'0', 's.supprime'=>'0'];
return DB::table('serveuraps AS s')
->select(DB::raw('s.nom as hostname'))
->join('machines AS m','m.id','=','s.machine_id')
->join('typeserveurs AS t','t.id','=','m.typeserveur_id')
->where($where)
->where('hostname','like','%'.$term.'%')
->get();
}
View:
<div class="col-md-12">
<div class="form-group">
<label class="col-md-3 control-label">{!! __('script.serveur') !!}</label>
<div class="col-md-4">
<input class="form-control" type="text" name="serveur" id="relance-serveur" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
</div>
</div>
Jquery/Ajax:
$(document).ready(function () {
// relance serveur autocomplete textbox
$('#relance-serveur').autocomplete({
source: function (request, response) {
alert(request.term)
$.ajax({
url: '/scripts/relanceCollection/collection',
dataType: 'json',
data: {
search: request.term
},
success: function (data) {
response(data);
}
});
},
});
});
I’m getting error when accessing the search
from js in controller.
I printed $request
but it showed the json data from model. how would I get the search
from js to controller so that I can search data based on that term ?
3
Answers
I got the result by adding
$.map
function in success function in JS. if anyone needs it, please refer below js code:The key you are sending is
search
, notterm
. Either change your controller code to reflect that, or change the ajax data.You aliased the wrong class. You don’t want an instance of a Facade, ever. If you want an instance of something you want the underlying instance, not the facade.
Now,
$request
would be an instance of that class and not the Facade,IlluminateSupportFacadesRequest
.