I’ve put together a few example queries and speed tests for them so you can learn how to build faster queries. Hope it helps someone. If it does leave a comment, thanks!
Example query relationship through whereHas
1 2 3 4 5 |
$data["gender_male"] = Customer::whereHas('tags', function($query) { $query->where('id', 44); //male })->count(); |

Analysis: slow as fk… 25.88s
Tweaked it to grab customers first and store them, then use the collection filter function.
1 2 3 4 5 6 7 8 9 10 11 |
$customers = Cache::get('cache.customers', function() { $data = Customer::select('id','first_name','last_name')->with('tags')->get(); Cache::put('cache.customers', $data, 10080); return $data; }); $data["gender_male"] = $customers->filter(function ($value, $key) { return $value->tags()->where('id', 44); //male })->count(); |

Analysis: much much faster!!! 2.39s
And then put it into Laravel cache.
1 2 3 4 5 6 7 8 9 |
$data["gender_male"] = Cache::get('cache.gender_male', function() { $data = $customers->filter(function ($value, $key) { return $value->tags()->where('id', 44); //male })->count(); Cache::put('cache.gender_male', $data, 10080); return $data; }); |

Another way to do it if your just after counts.
1 2 3 4 5 6 |
$data["gender_female"] = Cache::get('cache.gender_female', function() use ($customers) { $data = Tag::where('name','female')->first()->getCustomersCount(); Cache::put('cache.gender_female', $data, 10080); }); |
More coming soon…