Many-to-Many Automatic Cache Invalidation
Automatic invalidation can be quite tricky for Many-To-Many relationships because natively, there is not a specific event that gets triggered upon attach
, detach
, sync
or other many-to-many variations called directly on the relation method.
For many-to-many automatic cache invalidation, a package that will enable events for the many to many relationships is needed: chelout/laravel-relationship-events
Installing the package
Given the Laravel documentation's example on pivots, we might have the same example with User
and Role
.
Note: The HasBelongsToManyEvents
trait is the one that will respond to BelongsToMany
. Read more about Laravel Relationship Events to use the correct trait for your relationship:
For the observer to work, \Chelout\RelationshipEvents\Traits\HasRelationshipObservables
must also be implemented in the parent model (in this example, it's User
).
In the example above, the flushCacheOnUpdate
should be on the model from which you call the many-to-many relation. This will trigger automatic cache invalidation for the following query:
Upon triggering the ->attach()
method, the cache associated with the tag user:[user_id]:roles
will be flushed.
As you might have seen, the getCacheTagsToInvalidateOnUpdate
will also pass the related model on which the many-to-many relation will take action. In the above example, it will invalidate the roles of the user by using a Selective cache invalidation for specific tags.
Last updated
Was this helpful?