Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Last active December 11, 2019 02:04
Show Gist options
  • Save DarkGhostHunter/ec6a4ae14ca1a3d18e8f7397f1fe09e8 to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/ec6a4ae14ca1a3d18e8f7397f1fe09e8 to your computer and use it in GitHub Desktop.
A trait to cache responses or part of the controller logic.
<?php
namespace App\Http\Helpers;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
trait CachesResponses
{
/**
* Returns data for this request or caches it
*
* @param \Illuminate\Http\Request $request The request instance
* @param callable|string|\Closure $data The data to cache
* @param int $ttl The time to live the cached response. 60 seconds by default.
* @param null|string The key to use with the remember
* @return mixed
*/
protected function remember(Request $request, $callable, int $ttl = 60, string $key = null)
{
// First, we will check if the controller has a custom key for the cache. If there is,
// we will call the method for the string, otherwise we will create our convenient
// string. The latter is an MD5 hash of the full URL and the user identifier.
$key = $key ?? method_exists($this, 'requestCacheKey')
? $this->requestKey($request)
: 'request|' . md5($request->fullUrl() . optional($request->user())->getAuthIdentifier());
return Cache::remember($key, $ttl, fn () => is_callable($callback) ? $callback($request) : $this->$callback($request));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment