PHPackages                             unionworx/laravel-serializes-models-with-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. unionworx/laravel-serializes-models-with-cache

ActiveLibrary[Caching](/categories/caching)

unionworx/laravel-serializes-models-with-cache
==============================================

This package provides a drop-in replacement for Laravel's SerializesModels trait that leverages your application's cache when unserializing models.

0.3.0(1mo ago)21.2k↑96.2%MITPHPPHP ^8.3CI passing

Since Jun 12Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/Union-Worx/laravel-serializes-models-with-cache)[ Packagist](https://packagist.org/packages/unionworx/laravel-serializes-models-with-cache)[ Docs](https://github.com/Union-Worx/laravel-serializes-models-with-cache)[ RSS](/packages/unionworx-laravel-serializes-models-with-cache/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (4)Dependencies (15)Versions (6)Used By (0)

Laravel Serializes Models With Cache
====================================

[](#laravel-serializes-models-with-cache)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e8a1650c9c01bc5f6066043c06c56ae33f738f019cf5c4cc9698e72a502b0ad0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f756e696f6e776f72782f6c61726176656c2d73657269616c697a65732d6d6f64656c732d776974682d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/unionworx/laravel-serializes-models-with-cache)[![Total Downloads](https://camo.githubusercontent.com/7cb3b3ea84c19403d08d9cdf70b3bc5f7d07243dda1ba748474a7dd85b00a425/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f756e696f6e776f72782f6c61726176656c2d73657269616c697a65732d6d6f64656c732d776974682d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/unionworx/laravel-serializes-models-with-cache)[![GitHub Actions](https://github.com/unionworx/laravel-serializes-models-with-cache/actions/workflows/main.yml/badge.svg)](https://github.com/unionworx/laravel-serializes-models-with-cache/actions/workflows/main.yml/badge.svg)

This package provides a drop-in replacement for Laravel's SerializesModels trait that leverages your application's cache when unserializing models.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require unionworx/laravel-serializes-models-with-cache
```

Compatibility
-------------

[](#compatibility)

- Laravel: `10.x`, `11.x`, `12.x`, `13.x`
- PHP: `^8.3`

Usage
-----

[](#usage)

To use the `SerializesModelsWithCache` trait, simply replace Laravel's `SerializesModels` trait with `SerializesModelsWithCache` in your classes:

```
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use UnionWorx\LaravelSerializesModelsWithCache\SerializesModelsWithCache;
use App\Models\Message;

class SendMessage
{
    use Dispatchable, InteractsWithQueue, SerializesModelsWithCache;

    public Message $message;

    public function handle()
    {
        // Your job logic
    }
}
```

Under the hood this uses most of the default behavior of the `SerializesModels` trait, but will attempt to retrieve the model from the cache before querying the database. This uses the [remember](https://laravel.com/docs/11.x/cache#retrieve-store) feature of the Laravel cache to retrieve the model from the cache or uses the default `SerializesModels` behavior and stores the result.

### Attributes

[](#attributes)

You can further customize the caching behavior using attributes:

- **`CacheKey`**: Define a custom cache key for a specific property.
- **`CacheTTL`**: Set a custom Time-To-Live (TTL) for the cache entry of a property.
- **`CacheSkip`**: Skip caching for a specific property.

```
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheKey;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheTTL;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheSkip;
use App\Models\User;
use App\Models\Message;

class SendMessage
{
    use Dispatchable, InteractsWithQueue, SerializesModelsWithCache;

    #[CacheKey(key: 'custom_key_{id}')]
    #[CacheTTL(ttl: 120)]
    public Message $message;

    #[CacheSkip]
    public User $user;

    public function handle()
    {
        // Your job logic
    }
}
```

### Methods

[](#methods)

Alternatively, you can use the `cacheKey`, `cacheTTL`, and `cacheSkip` methods to customize the caching behavior:

```
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheKey;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheTTL;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheSkip;
use App\Models\User;
use App\Models\Message;

class SendMessage
{
    use Dispatchable, InteractsWithQueue, SerializesModelsWithCache;

    public Message $message;

    public User $user;

    public function handle()
    {
        // Your job logic
    }

    public function cacheKey(string $propertyName, mixed $id): ?string
    {
        if ($propertyName === 'message') {
            return 'custom_key_' . $id;
        }
    }

    public function cacheTTL(): array|DateInterval|DateTimeInterface|int|null
    {
        return [
            'message' => 120,
        ];
    }

    public function cacheSkip(): ?array
    {
        return [
            'user',
        ];
    }
}
```

### Cache Prefix

[](#cache-prefix)

By default, model restores are cached using a versioned key derived from the full Laravel `ModelIdentifier` payload. The generated key includes the model class, id, connection, loaded relations, and collection class when present, so restores with different relation graphs do not share the same cache entry. The generated key format starts with `model_restore_v2_`.

The generated default key is also binary-safe for non-UTF-8 queueable identifiers, including binary string IDs and associative composite identifiers.

If you provide a `#[CacheKey]` attribute or a `cacheKey()` method, that explicit key still wins exactly as provided. For generated default keys, you can further isolate the cache by adding a `cachePrefix()` method to your class. The prefix applies only to generated default keys and does not modify explicit custom keys.

```
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheKey;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheTTL;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheSkip;
use App\Models\Message;

class SendMessage
{
    use Dispatchable, InteractsWithQueue, SerializesModelsWithCache;

    #[CacheKey(key: 'custom_key_{id}')]
    public Message $message;

    public function handle()
    {
        // Your job logic
    }

    public function cachePrefix(): ?string
    {
        return get_class($this);
    }
}
```

### Cache Store

[](#cache-store)

By default, the cache store used is the default cache store defined in your Laravel configuration. You can override this by adding a `cacheStoreName` method to your class. The selected store is used for both generated default keys and explicit custom keys.

```
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheKey;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheTTL;
use UnionWorx\LaravelSerializesModelsWithCache\Attributes\CacheSkip;
use App\Models\Message;

class SendMessage
{
    use Dispatchable, InteractsWithQueue, SerializesModelsWithCache;

    #[CacheKey(key: 'custom_key_{id}')]
    public Message $message;

    public function handle()
    {
        // Your job logic
    }

    public function cacheStoreName(): ?string
    {
        return 'file';
    }
}
```

### Testing

[](#testing)

You can run the package tests via composer:

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on recent changes.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Christopher Carranza](https://github.com/ChristopherCarranza)

License
-------

[](#license)

MIT. Please see [License File](LICENSE.md) for more information.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance94

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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 ~239 days

Total

4

Last Release

33d ago

PHP version history (2 changes)0.1.0PHP ^8.0

0.2.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4485800?v=4)[Christopher Carranza](/maintainers/ChristopherCarranza)[@ChristopherCarranza](https://github.com/ChristopherCarranza)

---

Top Contributors

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

---

Tags

laravelcachemodelsunionworxserializeslaravel-serializes-models-with-cache

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/unionworx-laravel-serializes-models-with-cache/health.svg)

```
[![Health](https://phpackages.com/badges/unionworx-laravel-serializes-models-with-cache/health.svg)](https://phpackages.com/packages/unionworx-laravel-serializes-models-with-cache)
```

###  Alternatives

[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k55.0M619](/packages/laravel-scout)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/horizon

Dashboard and code-driven configuration for Laravel queues.

4.2k95.4M307](/packages/laravel-horizon)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k91.9k1](/packages/mike-bronner-laravel-model-caching)

PHPackages © 2026

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