$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<(int|string), mixed> * * @phpstan-ignore-next-line */ public static function getCached(): \Illuminate\Database\Eloquent\Collection { if (! Cache::has(static::getCacheKeyName())) { try { static::setCached(); } catch (QueryException $e) { report($e); return \Illuminate\Database\Eloquent\Collection::make(); } } 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(get_called_class(), 'cacheConditions')) { // @phpstan-ignore-next-line $conditions = collect(static::${'cacheConditions'})->all(); } Cache::put(static::getCacheKeyName(), static::queryCached(static::query()) ->where($conditions)->get() ->pipe(fn (Collection $collection) => \call_user_func([self::class, '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__ . '\\', '', get_called_class()); } }