diegobvasco / laravel-auth-cache
Cached Eloquent user provider with event-driven invalidation for Laravel
Fund package maintenance!
Requires
- php: ^8.4
- illuminate/contracts: ^11.0||^12.0||^13.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.1.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-arch: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
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
- Caching: When a user is retrieved via
retrieveById(), the provider caches the user record with the configured TTL. - Cache Key: Cache keys are generated as
{prefix}.{model_basename}.{id}(e.g.,auth.user.123). - Automatic Invalidation: When a model is updated or deleted, a
CacheInvalidationRequestedevent is dispatched. The registered listener automatically clears the corresponding cache entry. - Interface-Based Design: All components use interfaces and dependency injection, making them testable and extensible.
- 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 inconfig/auth-cache.php, or per-provider via thecache.prefixoverride inconfig/auth.php), or - provide a custom
CacheKeyGeneratorInterfaceimplementation 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 invalidatedidentifier- The model's identifier (ID)reason- Why invalidation occurred:updated,deleted, ormanual
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
nullfor 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
CacheInterfacenow exposesget(),put()andforget()instead ofremember(). The TTL is always a\DateTimeInterface(integers were ambiguous: Laravel interprets them as seconds, while this package's config is in minutes).CacheInvalidatorInterface::invalidate()takesstring $modelClassinstead ofobject $model.CachedUserDataonly models successful lookups:fromString(),fromNull(),from()and thetype/valuepayload fields were removed;toAuthenticatable()always returns a model or throws.CacheConfigurationproperties are no longer public; use the getters.CacheKey::equals()andCacheTtl::equals()were removed.- An invalid
AUTH_CACHE_TTL(empty or non-numeric) now falls back to60instead 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.