$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|\Illuminate\Support\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 * * @return void */ public static function removeCached(): void { Cache::forget(static::getCacheKeyName()); } /** * Put all instances into cache. * * @return void */ protected static function setCached(): void { $conditions = []; if (property_exists(get_called_class(), 'cacheConditions')) { $conditions = collect(get_called_class()::${'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 * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */ protected static function queryCached(Builder $query): Builder { return $query; } /** * Change query for cached elements * * @param \Illuminate\Support\Collection $results * @return \Illuminate\Support\Collection */ protected static function filterQuery(Collection $results): Collection { return $results; } /** * Get the class basename * * @return string */ protected static function getCacheKeyName(): string { return static::getCallClassBaseName(); } /** * Get the class basename * * @return string */ protected static function getCallClassBaseName(): string { return str_replace(__NAMESPACE__ . '\\', '', get_called_class()); } }