Skip to content

Instantly share code, notes, and snippets.

@adamgavlak
Created December 14, 2015 21:45
Show Gist options
  • Save adamgavlak/7d4e8f8acab1000da93f to your computer and use it in GitHub Desktop.
Save adamgavlak/7d4e8f8acab1000da93f to your computer and use it in GitHub Desktop.
Laravel middleware for caching routes
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Cache;
class CacheOrRetrieve
{
private $cacheTime = 10;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$key = $this->cacheKey($request->path());
if (Cache::has($key)) {
$content = Cache::get($key);
$response = response($content);
if ($this->isJson($content)) {
$response->header('Content-Type', 'application/json');
}
return $response;
}
$response = $next($request);
Cache::put($key, $response->getContent(), $this->cacheTime);
return $response;
}
private function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
private function cacheKey($path)
{
return 'route:' . str_replace('/', '-', $path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment