I have the following code that is working fine, I am trying to fetch about 50,000 cities in a searchable textfield using laravel but it takes alot of time and browser becoming inactive. How can I optimize so that it is fast.
public function searchCity()
{
$country = Country::with('states.cities')->find(231);
if ($country) {
$cities = $country->states->flatMap->cities->pluck('name')->toArray();;
return $cities;
} else {
return response()->json(['message' => 'Country not found'], 404);
}
}
and the ajax
$.ajax({
method: "GET",
url: "/searchcity",
success: function (response) {
townsTags = response;
startAutocomplete(townsTags, "#search_towns");
}
});
2
Answers
Why don’t you perform your search on the server side?
You could send the item you’re searching as query params:
And then search for specific result:
Also consider implementing lazy loading for the results. Display a few initial results and load more as the user scrolls down.
I would also like to suggest taking the approach of letting the backend do more of the work, as 9uifranco suggests.
Some initial thoughts and pointers;
startAutocomplete
. While this code can probably be optimized, doing the work on the frontend will probably hurt users with slower devices.'%' . $query . '%'
with$query . '%'
(removing the first %). Add an index to your database on name, and it will be much quicker.As for the backend query, you can limit cities in the query. No need to map.
If you still need states it can be something like