Last active
May 30, 2023 18:44
-
-
Save robertdrakedennis/803ff0358a2c3a185eea4cb9ce2c2537 to your computer and use it in GitHub Desktop.
Simple spatie media library caching to avoid n+1 queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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