PHPackages                             diegobvasco/laravel-auth-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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. diegobvasco/laravel-auth-cache

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

diegobvasco/laravel-auth-cache
==============================

This is my package laravel-auth-cache

1.0.3(2mo ago)04[2 PRs](https://github.com/diegobvasco/laravel-auth-cache/pulls)MITPHPPHP ^8.4CI passing

Since Feb 18Pushed 2mo agoCompare

[ Source](https://github.com/diegobvasco/laravel-auth-cache)[ Packagist](https://packagist.org/packages/diegobvasco/laravel-auth-cache)[ Docs](https://github.com/diegobvasco/laravel-auth-cache)[ GitHub Sponsors](https://github.com/diegobvasco)[ RSS](/packages/diegobvasco-laravel-auth-cache/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (22)Versions (9)Used By (0)

Laravel Auth Cache
==================

[](#laravel-auth-cache)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7f27cd6b44097b217ba1e3c326c93bf8fab5d9576eeacd062fab8c6feeb47c33/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646965676f62766173636f2f6c61726176656c2d617574682d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/diegobvasco/laravel-auth-cache)[![GitHub Tests Action Status](https://camo.githubusercontent.com/15b33314383eec7233f9742c7f76f2ded6b3f345633a93d71c926a1d8a447aea/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f646965676f62766173636f2f6c61726176656c2d617574682d63616368652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/diegobvasco/laravel-auth-cache/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/4a9a5053b31a03d4e372a5897dce49d5d24c8129bef639442c6fd95c100af98e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f646965676f62766173636f2f6c61726176656c2d617574682d63616368652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/diegobvasco/laravel-auth-cache/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/7b5bf9bbdf787f830cabdf10b3d85c9c9c730af6b31976890f75f8ea6e2029d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646965676f62766173636f2f6c61726176656c2d617574682d63616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/diegobvasco/laravel-auth-cache)

A Laravel authentication caching package that provides optimized user retrieval with automatic cache invalidation. Built with SOLID principles, dependency injection, and event-driven architecture for maintainable and testable code.

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

[](#installation)

You can install the package via composer:

```
composer require diegobvasco/laravel-auth-cache
```

You can publish the config file with:

```
php artisan vendor:publish --tag="laravel-auth-cache-config"
```

This is the contents of the published config file:

```
return [
    'cache' => [
        'enabled' => (bool) env('AUTH_CACHE_ENABLED', true),
        'ttl' => (int) env('AUTH_CACHE_TTL', 60),
        'store' => env('AUTH_CACHE_STORE'),
        'prefix' => env('AUTH_CACHE_PREFIX', 'auth'),
    ],
];
```

Usage
-----

[](#usage)

### 1. Configure the Auth Provider

[](#1-configure-the-auth-provider)

Update your `config/auth.php` file to use the `cachedEloquent` provider:

```
return [
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'cachedEloquent',
            'model' => App\Models\User::class,
        ],
    ],
];
```

### 2. Configure Cache Settings

[](#2-configure-cache-settings)

Publish the config file and adjust the cache settings in `config/auth-cache.php`:

```
return [
    'auth' => [
        'cache' => [
            'enabled' => env('AUTH_CACHE_ENABLED', true),
            'ttl' => env('AUTH_CACHE_TTL', 60),
            'store' => env('AUTH_CACHE_STORE', null),
            'prefix' => env('AUTH_CACHE_PREFIX', 'auth'),
        ],
    ],
],
```

#### Configuration Options

[](#configuration-options)

- **enabled**: Enable or disable caching (default: `true`)
- **ttl**: Cache time-to-live in minutes (default: `60`)
- **store**: Specific cache store to use (default: `null` - uses default cache store)
- **prefix**: Cache key prefix (default: `'auth'`)

### 3. Clearing cache

[](#3-clearing-cache)

Both the trait and the observer clear the cache only listen Eloquent model events `updated` and `deleted`.

#### Using trait

[](#using-trait)

Add the `HasCachedAuthProvider` trait to your user model:

```
use DiegoVasconcelos\AuthCache\Concerns\HasCachedAuthProvider;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasCachedAuthProvider;

    // ...
}
```

#### Using observer

[](#using-observer)

Register the observer `CachedAuthObserver` to your user model:

```
use DiegoVasconcelos\AuthCache\Observers\CachedAuthObserver;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;

#[ObservedBy(CachedAuthObserver::class)]
class User extends Authenticatable
{
    // ...
}
```

The example use `ObservedBy` to register the observer but you can use traditional way in `AppServiceProvider`.

### Per-Guard Configuration

[](#per-guard-configuration)

You can override cache settings per-guard in `config/auth.php`:

```
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
        'cache' => [
            'ttl' => 120, // Override to 2 minutes for web
        ],
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'cache' => [
            'enabled' => false, // Disable cache for API
        ],
    ],
],
```

### Custom Cache Store

[](#custom-cache-store)

Use a specific cache store for auth caching by setting the `AUTH_CACHE_STORE` environment variable:

```
CACHE_DRIVER=redis
AUTH_CACHE_STORE=redis
```

### How It Works

[](#how-it-works)

1. **Caching**: When a user is retrieved via `retrieveById()`, the provider caches the user record with the configured TTL.
2. **Cache Key**: Cache keys are generated as `{prefix}.{model_basename}.{id}` (e.g., `auth.user.123`).
3. **Automatic Invalidation**: When a model is updated or deleted, a `CacheInvalidationRequested` event is dispatched. The registered listener automatically clears the corresponding cache entry.
4. **Interface-Based Design**: All components use interfaces and dependency injection, making them testable and extensible.
5. **Configurable**: You can enable/disable caching, adjust TTL, use different cache stores, and customize the cache key prefix.

Architecture
------------

[](#architecture)

This package is built using SOLID principles and Laravel best practices:

### Interface-Based Design

[](#interface-based-design)

All cache operations are defined by interfaces:

- **CacheInterface** - Core cache operations (remember, forget, isEnabled)
- **CacheKeyGeneratorInterface** - Strategy for generating cache keys
- **CacheInvalidatorInterface** - Handles cache invalidation
- **CacheConfigurationInterface** - Configuration access

### Dependency Injection

[](#dependency-injection)

All components are resolved through Laravel's service container, providing:

- Easy testing with mocks
- Ability to replace implementations
- Loose coupling between components

### Event-Driven Cache Invalidation

[](#event-driven-cache-invalidation)

- Events decouple cache clearing from models
- Listeners handle invalidation logic
- Multiple listeners can respond to cache events

Events
------

[](#events)

### CacheInvalidationRequested

[](#cacheinvalidationrequested)

Dispatched when cache should be invalidated (on model update, delete, or manual request).

**Event Properties:**

- `model` - The model instance being invalidated
- `identifier` - The model's identifier (ID)
- `reason` - Why invalidation occurred: `updated`, `deleted`, or `manual`

**Example: Listen to Invalidation Events**

```
use DiegoVasconcelos\AuthCache\Events\CacheInvalidationRequested;

Event::listen(CacheInvalidationRequested::class, function ($event) {
    Log::info("Cache cleared for {$event->reason}: {$event->identifier}");
});
```

Extending
---------

[](#extending)

### Custom Cache Key Generator

[](#custom-cache-key-generator)

Create your own key generation strategy:

```
use DiegoVasconcelos\AuthCache\Contracts\CacheKeyGeneratorInterface;

class CustomKeyGenerator implements CacheKeyGeneratorInterface
{
    public function generate(string $modelClass, mixed $identifier): string
    {
        return "custom.{$modelClass}.{$identifier}";
    }
}

// Register in AppServiceProvider
app()->bind(
    CacheKeyGeneratorInterface::class,
    CustomKeyGenerator::class
);
```

### Custom Cache Invalidation

[](#custom-cache-invalidation)

Implement your own invalidation logic:

```
use DiegoVasconcelos\AuthCache\Contracts\CacheInvalidatorInterface;

class CustomInvalidator implements CacheInvalidatorInterface
{
    public function invalidate(object $model, mixed $identifier): void
    {
        // Your custom logic (e.g., log, broadcast, etc.)
        Cache::forget("custom.key.{$identifier}");
    }
}

app()->bind(
    CacheInvalidatorInterface::class,
    CustomInvalidator::class
);
```

### Custom Configuration

[](#custom-configuration)

Modify configuration at runtime:

```
use DiegoVasconcelos\AuthCache\Contracts\CacheConfigurationInterface;

app()->afterResolving(CacheConfigurationInterface::class, function ($config) {
    // Customize based on environment, user roles, etc.
});
```

Testing
-------

[](#testing)

```
composer test
```

The package includes comprehensive tests:

- Unit tests for all components
- Integration tests for provider, trait, and observer
- Architecture tests ensuring code quality

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

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

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Diego Vasconcelos](https://github.com/diegobvasco)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance85

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.4% 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 ~9 days

Total

4

Last Release

60d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e2517096d7186d249374898ba51819d519921ddf32d6100d4905dbfba83c4c5c?d=identicon)[diegobvasco](/maintainers/diegobvasco)

---

Top Contributors

[![diegobvasco](https://avatars.githubusercontent.com/u/11035163?v=4)](https://github.com/diegobvasco "diegobvasco (17 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laraveldiegobvascolaravel-auth-cache

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/diegobvasco-laravel-auth-cache/health.svg)

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

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[spatie/laravel-login-link

Quickly login to your local environment

4381.2M1](/packages/spatie-laravel-login-link)[ryangjchandler/laravel-cloudflare-turnstile

A simple package to help integrate Cloudflare Turnstile.

438896.6k2](/packages/ryangjchandler-laravel-cloudflare-turnstile)[spatie/laravel-passkeys

Use passkeys in your Laravel app

444494.4k16](/packages/spatie-laravel-passkeys)

PHPackages © 2026

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