I would like to remove a certain cache entry if a new relation (belongsToMany or manyToMany) entry was created on a model. So I searched for a way to perform an action after a relation entry was created / removed.
I kinda guessed it’s the afterSave() method within the Relations Model, but it’s not.
public function boot()
{
MyModel::extend(function ($model) {
$model->bindEvent('model.relation.attach', function () use ($model) {
Cache::tags('my', 'tags')->forget('name_' . $model->id);
});
$model->bindEvent('model.relation.detach', function () use ($model) {
Cache::tags('my', 'tags')->forget('name_' . $model->id);
});
});
}
I know I could also filter for the correct relation, but since all relations of that model should trigger the cache remove, I do not see this as necessary, or did I miss something?
Is there a reason why this have to be done via bindEvent() and why there’s no easier solution like an afterSave() method in the Model? Maybe an afterRelationChange()?
I can imagine this is a common problem if you work with relations…