Reputation: 695
I have 4 tables :
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 ?
Upvotes: 0
Views: 1008
Reputation: 8927
1) Loops: Your Type
, City
& State
modals are not gonna change for each loop. It's better to query them before that.
$types = Type::all();
$cities = City::all();
$states = State::all();
foreach ($slug as slug) {
2) Cache: Caching for these three modals seems appropriate.
3) Since I don't want to repeat, please go through this thread on how to optimize. It talks about proper use of select(), Indexing, data types and some more.
Keep me posted in the comments below. Cheers!
Upvotes: 2