I have 4 tables :
- ads (id, name, type_id ,city_id)
- types (id, slug, name)
- cities (id, slug, name) (37000 entries)
- states (id, slug, name) (120 entries)
I can have a url like this : https://example.com/ad,type,city.html or like this : https://example.com/ad,type,state.html
I need to do a search ads filter by slugs and i'm doing like this to get my ads filtered :
$slugs = explode(',', $slugs);
$ads = Ad::where('is_active', true)->get();
foreach ($slug as slug){
$types = Type::all();
if ($types->contains('slug', $slug)) {
$type = $types->first(function ($value) use ($slug) {
return $value->slug == $slug;
});
$ads = $ads->where('type_id', $type->id);
$cities = City::all();
if ($cities->contains('slug', $slug)) {
$city = $cities->first(function ($value) use ($slug) {
return $city->slug == $slug;
});
$ads = $ads->where('city_id', $city->id);
$states = State::all();
if ($states->contains('slug', $slug)) {
$state = $states->first(function ($value) use ($slug) {
return $state->slug == $slug;
});
$ads = $ads->where('state_id', $state->id);
}
return $ads;
}
This works. But as i have many cities it can be slow (between 1 and 2 seconds). How can i improve this ? I was thinking to use cache like memcached to put cities on it, but the result doesn't change so much. Maybe is the way i builded it who is wrong ?