Computed fields slow down all requests #7202
-
Good chance I'm being dumb here as I'm new to Computed fields. In a service provider I have the following: Collection::computed('news_articles', 'reactions', function ($article) {
return collect(config('site.reactions'))->reduce(
function ($output, $reaction, $key) use ($article) {
if ($article[$key . '_reactions']->count()) {
$output .= $reaction['emoji'] . $article[$key . '_reactions']->count();
}
return $output;
},
''
);
}); This works great, but after a bunch of digging I've found out it's significantly slowing down my front end when I try and load the How can I only set that field for control panel requests? Also, any idea's why this would be generating 38,000+ events (I can see these are mostly Statamic\Events\UserBlueprintFound events in debugbar) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
If the answer is that I should be caching that, how can I ensure that cache gets invalidated when things on the page change? |
Beta Was this translation helpful? Give feedback.
-
Wrap it in a Blink or Cache so it's not executed multiple times. https://statamic.dev/computed-values#performance Collection::computed('news_articles', 'reactions', function ($article) {
$key = 'article_reaction-'.$article->id();
return Cache::rememberForever($key, function () { // or Blink::once()
// ...
});
}); You can invalidate it by listening for Event::listen(function (EntrySaved $event) {
Cache::forget('article_reaction-'.$event->entry->id());
}); If you're using Blink, nothing is actually cached since it's only for that request. You don't need to invalidate it. |
Beta Was this translation helpful? Give feedback.
Wrap it in a Blink or Cache so it's not executed multiple times. https://statamic.dev/computed-values#performance
You can invalidate it by listening for
EntrySaved
If you're using Blink, nothing is actually cached since it's only for that request. You don't need to invalidate it.