Skip to content

Instantly share code, notes, and snippets.

@robertdrakedennis
Last active May 30, 2023 18:44
Show Gist options
  • Save robertdrakedennis/803ff0358a2c3a185eea4cb9ce2c2537 to your computer and use it in GitHub Desktop.
Save robertdrakedennis/803ff0358a2c3a185eea4cb9ce2c2537 to your computer and use it in GitHub Desktop.
Simple spatie media library caching to avoid n+1 queries
<?php
namespace App\Traits\Models;
trait CachesMediaUrl
{
/**
* Caches Media urls to avoid duplicate calls
*
* @param string $collectionName
* @return mixed
*/
public function getMediaUrl(string $collectionName): string
{
$media = \Cache::remember($this->getCacheKey($collectionName), $this->expiresIn(), function () use ($collectionName) {
return $this->getFirstMediaUrl($collectionName);
});
return $media;
}
/**
* Forgets media url cache.
*
* @param string $collectionName
* @return bool
*/
public function flushMediaCache(string $collectionName): bool
{
return \Cache::forget($this->getCacheKey($collectionName));
}
/**
* Unique cache key to avoid overriding other cache keys using the trait.
*
* @param string $collectionName
* @return string
*/
protected function getCacheKey(string $collectionName): string
{
return (string) class_basename($this) . $this->id . $collectionName;
}
/**
* Sets TTL for remember function. Override in base class to change cache time
*
* @return \Illuminate\Support\Carbon
*/
protected function expiresIn(): \Illuminate\Support\Carbon
{
return now()->addMinutes(5);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment