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.
You can install the package via composer:
composer require diegobvasco/laravel-auth-cacheYou 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'),
],
];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,
],
],
];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'),
],
];-
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')
Both the trait and the observer clear the cache only listen Eloquent model events updated and deleted.
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;
// ...
}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.
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
],
],
],Use a specific cache store for auth caching by setting the AUTH_CACHE_STORE environment variable:
CACHE_DRIVER=redis
AUTH_CACHE_STORE=redis-
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.
This package is built using SOLID principles and Laravel best practices:
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
All components are resolved through Laravel's service container, providing:
- Easy testing with mocks
- Ability to replace implementations
- Loose coupling between components
- Events decouple cache clearing from models
- Listeners handle invalidation logic
- Multiple listeners can respond to cache events
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, 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}");
});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
);Implement your own invalidation logic:
use DiegoVasconcelos\AuthCache\Cache\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
);Modify configuration at runtime:
use DiegoVasconcelos\AuthCache\Cache\Contracts\CacheConfigurationInterface;
app()->afterResolving(CacheConfigurationInterface::class, function ($config) {
// Customize based on environment, user roles, etc.
});composer testThe package includes comprehensive tests:
- Unit tests for all components
- Integration tests for provider, trait, and observer
- Architecture tests ensuring code quality
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.