$cacheConditions * Eloquent condition to cache elements (to be used in where statement). */ trait IsCachedAsCollection { /** * Get all available instances from cache. * If cache was reset, it will fetch them from DB. * * @return \Illuminate\Database\Eloquent\Collection|Collection<(int|string), mixed> */ public static function getCached(): Collection { if (! Cache::has(static::getCacheKeyName())) { try { static::setCached(); } catch (QueryException $e) { report($e); return \collect(); } } return Cache::get(static::getCacheKeyName()); } /** * Remove cached elements */ public static function removeCached(): void { Cache::forget(static::getCacheKeyName()); } /** * Put all instances into cache. */ protected static function setCached(): void { $conditions = []; if (property_exists(static::class, 'cacheConditions')) { $conditions = collect(static::class::${'cacheConditions'})->all(); } Cache::put(static::getCacheKeyName(), static::queryCached(static::query()) ->where($conditions)->get() ->pipe(fn (Collection $collection): Collection => \call_user_func(self::filterQuery(...), $collection))); } /** * Change query for cached elements */ protected static function queryCached(Builder $query): Builder { return $query; } /** * Change query for cached elements */ protected static function filterQuery(Collection $results): Collection { return $results; } /** * Get the class basename */ protected static function getCacheKeyName(): string { return static::getCallClassBaseName(); } /** * Get the class basename */ protected static function getCallClassBaseName(): string { return str_replace(__NAMESPACE__ . '\\', '', static::class); } }