PHPackages                             brekitomasson/laravel-tagged-cache - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. brekitomasson/laravel-tagged-cache

ActiveLibrary[Caching](/categories/caching)

brekitomasson/laravel-tagged-cache
==================================

A wrapper around the cache implementation to reduce complexity regarding caching in your Models

v2.0.6(5mo ago)191.6kMITPHPPHP ^8.2

Since Sep 17Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/BrekiTomasson/laravel-tagged-cache)[ Packagist](https://packagist.org/packages/brekitomasson/laravel-tagged-cache)[ RSS](/packages/brekitomasson-laravel-tagged-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (4)Versions (10)Used By (0)

Laravel Tagged Cache
====================

[](#laravel-tagged-cache)

A fairly straight-forward wrapper around the cache implementation to reduce complexity regarding caching in your Models. It has no external dependencies or configuration, and should "just work" out of the box.

Note, however, that this package requires you to be using a Cache implementation that supports tags. This means that it **will not work** if you are using `file`, `dynamodb` or `database` cache drivers.

Installation
============

[](#installation)

```
composer require brekitomasson/laravel-tagged-cache
```

Usage
=====

[](#usage)

In any Laravel Models, just `use BrekiTomasson\LaravelTaggedCache\HasTaggedCache`, and you will be able to create reliable caches that do not require a bunch of special handling regarding your cache keys. Instead of needing to come up with complex naming rules for your cache keys, you can use the same cache key for everything, as the differentiation will be done using the cache tags instead. This allows you to do things like:

```
public function getDisplayNameAttribute(): string
{
  return $this->taggedCache()->remember(
      key: 'displayname',
      ttl: now()->addHour(),
      callback: fn () => $this->nickname ?? $this->name ?? $this->email,
  );
}
```

This method, if in your `User` model, will store the cache key `displayname` with the tags `users` and `user:23` when used to get the `display_name` attribute for a user with the ID of 23.

You can also provide any amount of additional strings to the `taggedCache()` method, and those strings will be added to the list of tags. If, for example, you put something like this in your `BlogEntry` model:

```
public function getContentHtml(): string
{
    return $this->taggedCache('markdown')->remember(
        key: 'content:html',
        ttl: now()->addHour(),
        callback: fn () => Markdown::parse($this->content)->toHtml(),
    );
}
```

Then the `content:html` key will be tagged with `blog_entries`, `blog_entry:25`, and `markdown`. This allows you to do `Cache::tags('markdown')->flush()` if you've just made changes to your Markdown implementation and want all Markdown-related caches in all models to be cleared. Since a cache key will only get a hit if **all** tags match, this means that anything tagged with `markdown` in this way will automatically be forgotten, no matter which model it may be connected to.

Advanced Usage and Recommendations
==================================

[](#advanced-usage-and-recommendations)

1 - Cache Invalidation *(optional, but recommended!)*
-----------------------------------------------------

[](#1---cache-invalidation-optional-but-recommended)

[They say](https://martinfowler.com/bliki/TwoHardThings.html) that there are only two hard things in Computer Science: cache invalidation and naming things. Since this package makes it so much easier to cache things, you might be more willing to put things in your cache than you're used to, meaning you'll be more prone to get cache-related problems.

The normal way of working would be to build Observers that track changes to your models and flush caches based on which attributes have been modified, but this package offers a shortcut. By implementing a single method in your model, all caches for that specific instance of that model will be flushed. For example, if you were to put this in your Model:

```
public function flushTaggedCacheOnAttributeUpdate(): array
{
    return ['name', 'display_name', 'status'];
}
```

With this method in place, if you were to `ModelName::find(132)->update(['display_name' => 'ACME Systems']);` the package would automatically flush all caches related to that row, as the attribute `display_name` is listed inside the array returned by `flushTaggedCacheOnAttributeUpdate()`. Caches for other rows in that model will remain in place. This is the equivalent of building a Model Observer with a method like:

```
public function updated(ModelName $model): void
{
    if ($model->isDirty(['name', 'display_name', 'status'])) {
        $model->taggedCache()->flush();
    }
}
```

If you want the tagged cache to be flushed when any attribute is changed in your model, you can use the `'*'` wildcard:

```
public function flushTaggedCacheOnAttributeUpdate(): array
{
    return ['*'];
}
```

> Note: Caches will **always** be flushed for rows that are deleted. This behavior cannot be disabled.

2 - Getting and Caching a Single Attribute
------------------------------------------

[](#2---getting-and-caching-a-single-attribute)

Instead of having to write `$this->taggedCache()->remember('name', now()->addDay(), fn () => $this->name)` to get a cached instance of a single attribute from a model, there's a simple helper function available. The code above can be rewritten: `$this->getCachedAttribute('name')`. The cache is stored with a key named after the attribute for 24 hours.

Under the hood, it uses Laravel's own `getAttribute()` method, which means you can use it to return relationships and attributes made available through Mutators and/or Accessor functions, and it takes your `$casts` into account.

3 - Personalizing the Name of the Cache Tags
--------------------------------------------

[](#3---personalizing-the-name-of-the-cache-tags)

By default, the name of the database table underlying the Model will be used as a basis for the Cache tags. If your model is `Country` and the underlying database table is `countries`, then `Country::find(23)->taggedCache()` will use the tags `countries` and `country:23`. The latter is generated using Laravel's `Str::singular()` method.

To override what base name to use in your cache tags, you can implement the `getCacheTagIdentifier()` method in your model. Any string returned by this method will automatically be converted into snake\_case, but please try to keep any implementation of this to a plural string. For example:

```
public function getCacheTagIdentifier(): string
{
    return 'Comic Books';
}
```

If this method were in your model, then `Model::find(42)->taggedCache()` would use the tags `comic_books` and `comic_book:42`.

4 - Cache Duration Helper
-------------------------

[](#4---cache-duration-helper)

Instead of relying on things like `now()->addDays(3)` when setting up how long a cache key should be remembered, you could use [`BrekiTomasson/Seconds`](https://github.com/BrekiTomasson/Seconds) to write cleaner code and have a better overview of how things works. This package is not included in `Laravel-Tagged-Cache`, but is recommended.

```
public function getOpenTicketCount(): int
{
    return $this->taggedCache()->remember(
        'open-tickets',
        Seconds::minutes(3),
        fn() => $this->tickets->whereNotIn('status', [TicketStatus::CLOSED, TicketStatus::PENDING])->count();
    );
}
```

Copyright / License
===================

[](#copyright--license)

This package is distributed under an MIT license. See the `LICENSE` file for more information.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance70

Regular maintenance activity

Popularity26

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~166 days

Recently: every ~261 days

Total

8

Last Release

168d ago

Major Versions

v1.0.0 → v2.0.02022-10-24

PHP version history (2 changes)v1.0.0PHP ^8.1

v2.0.5PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/2005bc0510625184565d645acd62c9e54cbb1b692586276728e2293d2ce9b831?d=identicon)[Breki](/maintainers/Breki)

---

Top Contributors

[![BrekiTomasson](https://avatars.githubusercontent.com/u/7026735?v=4)](https://github.com/BrekiTomasson "BrekiTomasson (15 commits)")

### Embed Badge

![Health badge](/badges/brekitomasson-laravel-tagged-cache/health.svg)

```
[![Health](https://phpackages.com/badges/brekitomasson-laravel-tagged-cache/health.svg)](https://phpackages.com/packages/brekitomasson-laravel-tagged-cache)
```

###  Alternatives

[genealabs/laravel-model-caching

Automatic caching for Eloquent models.

2.4k4.8M26](/packages/genealabs-laravel-model-caching)[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[mikebronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k127.1k1](/packages/mikebronner-laravel-model-caching)[laragear/cache-query

Remember your query results using only one method. Yes, only one.

272122.8k](/packages/laragear-cache-query)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k2.0k1](/packages/mike-bronner-laravel-model-caching)[iazaran/smart-cache

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

2057.2k](/packages/iazaran-smart-cache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
