Search by

diegobvasco / laravel-auth-cache

diegobvasco

Cached Eloquent user provider with event-driven invalidation for Laravel

Package info

github.com/diegobvasco/laravel-auth-cache

pkg:composer/diegobvasco/laravel-auth-cache

Fund package maintenance!

diegobvasco

Statistics

Installs: 66

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v3.0.0 2026-11-12 14:29 UTC

This package is auto-updated.

Last update: 2026-11-12 14:29:25 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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

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'),
    ],
];

Invalidation is aware of these overrides: when a model is updated or deleted, the package clears the cache entry on every store and prefix combination its cachedEloquent providers are configured to use — including processes (like queue workers) where the providers themselves were never resolved.

Usage

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

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

return [
    '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

  • 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

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

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

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

You can override cache settings per-provider in config/auth.php by adding a cache key to the provider definition. These values are merged on top of the global config/auth-cache.php settings:

'providers' => [
    'users' => [
        'driver' => 'cachedEloquent',
        'model' => App\Models\User::class,
        'cache' => [
            'ttl' => 120, // Override to 120 minutes for this provider
        ],
    ],
    'api_users' => [
        'driver' => 'cachedEloquent',
        'model' => App\Models\ApiUser::class,
        'cache' => [
            'enabled' => false, // Disable cache for this provider
        ],
    ],
],

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

  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.

Cache keys and collisions

Cache keys use the model basename ({prefix}.{model_basename}.{id}), so two distinct auth models sharing the same basename — for example App\Models\Admin\User and App\Models\Client\User — produce the same key (auth.user.42) and will overwrite each other's cache entries.

If your application has more than one auth model with the same basename, either:

  • give each provider its own prefix (globally in config/auth-cache.php, or per-provider via the cache.prefix override in config/auth.php), or
  • provide a custom CacheKeyGeneratorInterface implementation that keys on the fully-qualified class name (see Custom Cache Key Generator).

Architecture

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

Interface-Based Design

All cache operations are defined by interfaces:

  • CacheInterface - Core cache operations (get, put, forget)
  • CacheKeyGeneratorInterface - Strategy for generating cache keys
  • CacheInvalidatorInterface - Handles cache invalidation
  • CacheConfigurationInterface - Configuration access

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

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

Events

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

Custom Cache Key Generator

Create your own key generation strategy:

use DiegoVasconcelos\AuthCache\Cache\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

Implement your own invalidation logic:

use DiegoVasconcelos\AuthCache\Cache\Contracts\CacheInvalidatorInterface;

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

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

Custom Configuration

Modify configuration at runtime:

use DiegoVasconcelos\AuthCache\Cache\Contracts\CacheConfigurationInterface;

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

Custom Cache Store Wrapper

Implement your own cache operations:

use DiegoVasconcelos\AuthCache\Cache\Contracts\CacheInterface;

class CustomCache implements CacheInterface
{
    public function get(string $key): mixed { /* ... */ }

    public function put(string $key, mixed $value, \DateTimeInterface $expiresAt): bool { /* ... */ }

    public function forget(string $key): void { /* ... */ }
}

app()->bind(CacheInterface::class, CustomCache::class);

Upgrading from 2.x to 3.0

Behavior changes

  • Cache misses are no longer cached. A lookup for a user that does not exist always hits the database instead of caching null for the full TTL.
  • Corrupted or legacy cache entries are treated as misses. Entries whose shape changed (e.g. 2.x type: "null" entries) are discarded and rebuilt from the database. Entries whose model class was renamed no longer fatal the request.
  • Non-array values found at a cache key are ignored and re-cached from the database.

API changes

  • CacheInterface now exposes get(), put() and forget() instead of remember(). The TTL is always a \DateTimeInterface (integers were ambiguous: Laravel interprets them as seconds, while this package's config is in minutes).
  • CacheInvalidatorInterface::invalidate() takes string $modelClass instead of object $model.
  • CachedUserData only models successful lookups: fromString(), fromNull(), from() and the type/value payload fields were removed; toAuthenticatable() always returns a model or throws.
  • CacheConfiguration properties are no longer public; use the getters.
  • CacheKey::equals() and CacheTtl::equals() were removed.
  • An invalid AUTH_CACHE_TTL (empty or non-numeric) now falls back to 60 instead of throwing, and the TTL is not validated at all when caching is disabled.

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

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.