My code is like below.
$('#restaurant').select2({
ajax: {
url: '{{url('/')}}/admin/vendor/get-restaurants',
data: function (params) {
return {
q: params.term, // search term
all:true,
page: params.page
};
},
processResults: function (data) {
return {
results: data
};
},
__port: function (params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
});
Here is the function of the controller.
public function get_restaurants(Request $request){
$zone_ids = isset($request->zone_ids)?(count($request->zone_ids)>0?$request->zone_ids:[]):0;
$data = Restaurant::join('zones', 'zones.id', '=', 'restaurants.zone_id')
->when($zone_ids, function($query) use($zone_ids){
$query->whereIn('restaurants.zone_id', $zone_ids);
})
->where('restaurants.name', 'like', '%'.$request->q.'%')
->limit(8)
->orderBy('restaurants.name', 'ASC')
->get([DB::raw('restaurants.id as id, CONCAT(restaurants.name, " (", zones.name,")") as text')]);
if(isset($request->all))
{
$data[]=(object)['id'=>'all', 'text'=>'All'];
}
return response()->json($data);
}
If I write any thing in Input Search Box it is not working.
CodePudding user response:
I don't know what is the problem with your code however I will tell you my way to do it.
It's very simple just loop over your resturants variable in select and in your script just init the select2.
In blade file:
<select id="restaurant">
@foreach($resturants as $resturant)
<option value="{{ $resturant->id }}">{{ $resturant->name }}</option>
@endforeach
</select>
In script
$('#restaurant').select2();
CodePudding user response:
you need to give return response in form of select2 like this
foreach ($restaurants as $restaurant) {
$response[] = array(
"id" => $restaurant->id,
"text" => $restaurant->name
);
}
return response()->json($response);