Repository navigation
How should I handle cache invalidation when related Eloquent models are updated? #61102
|
I have a Laravel application where I cache data for performance. Some cached data depends on multiple related Eloquent models. For example, I have: $subject = Subject::with('nodes.resources')->find($id);
Cache::remember(
"subject:{$id}",
now()->addDay(),
fn () => $subject
);The problem is that when a I could manually clear the subject cache from every observer, but as the application grows, this starts becoming difficult to maintain. What would be the recommended Laravel approach for handling this? Should I:
I'm particularly interested in how you would design this for a larger Laravel application where the relationships and cached queries may become more complex. What would be considered the most maintainable approach in Laravel? |
Replies: 1 comment
|
For a larger Laravel application, I’d prefer explicit cache invalidation, but keep it centralized rather than scattering For example, when a Cache::forget("subject:{$subjectId}");I wouldn't rely on cache tags to automatically handle Eloquent relationships—they don't understand your dependency graph. Also, avoid caching large Eloquent relationship trees unless necessary. Cache expensive query results or computed data where possible. For more complex/high-churn caches, versioned keys can be useful: $version = Cache::get("subject:{$id}:version", 1);
$key = "subject:{$id}:v{$version}";Then increment the version whenever related data changes. So, in short: centralized explicit invalidation for most applications; versioned keys when the dependency graph becomes complex. |
For a larger Laravel application, I’d prefer explicit cache invalidation, but keep it centralized rather than scattering
Cache::forget()calls everywhere.For example, when a
NodeorResourcechanges, invalidate the affectedSubjectcache from an observer or service:I wouldn't rely on cache tags to automatically handle Eloquent relationships—they don't understand your dependency graph.
Also, avoid caching large Eloquent relationship trees unless necessary. Cache expensive query results or computed data where possible.
For more complex/high-churn caches, versioned keys can be useful: