I am trying to fetch a list of cities that has more than 40,000 cities, My issue is how to optimize since my browser keeps being responsive when loading the cities.
In Laravel Controller I have,
public function getCities(Request $request)
{
$query = $request->input('query');
$cities = UsCities::where('CITY', 'like', '%' . $query . '%')->get()->pluck('CITY')->toArray();
return response()->json($cities);
}
and the ajax code
$.ajax({
method: "GET",
url: '{{ route("get.cities")}}',
data: { query: $('#city-selected').val() },
success: function (response) {
townsTags = response;
startAutocomplete(townsTags, "#city-selected");
}
});
function startAutocomplete(availableTags, inputSelector) {
$(inputSelector).autocomplete({
source: availableTags
});
}
2
Answers
If you want to optimize your search method when users type the city in the input field, you need to make the condition in your JS with the following:
Below is the code that you can try:
change 3 or 500 depending on when you want to start the execution.
You may use Eloquent ORM: API Resources with collections in controller.