Laravel – Forget cache on save

  • Post category:Snippets

As highlighted by Povilas Korop (@PovilasKorop) on Twitter: in Laravel, you can call a static “saved” function on your model to forget the cached values with a specific key.

Let’s say you have a collection of posts with a cache key of "posts" and you want to forget that cache key when a new post is stored or updated. You can call the static::saved() function on your model and forget the cache.

class Post extends Model
{
  public static function boot()
  {
    parent::boot();
    static::saved(function () {
      Cache::forget('posts');
    });
  }
}