Skip to content

Instantly share code, notes, and snippets.

@trouttdev
Created January 11, 2017 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trouttdev/ec7fc48351641e9289a31404884221c8 to your computer and use it in GitHub Desktop.
Save trouttdev/ec7fc48351641e9289a31404884221c8 to your computer and use it in GitHub Desktop.
Simple Laravel 5 response caching
<?php
namespace App\Http\Middleware;
use Closure;
use Cache;
class CacheResponse
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$key = $this->generateKey($request->fullUrl());
if (Cache::has($key)) {
return response(Cache::get($key));
}
return $next($request);
}
/**
* Handle caching of a request if it doesn't already exist
*/
public function terminate($request, $response)
{
$key = $this->generateKey($request->fullUrl());
// if the cache key doesn't exist then we store the whole response
if (!Cache::has($key)) {
// cache for 24 hours
Cache::put($key, $response->getContent(), 1440);
}
}
protected function generateKey($url)
{
return 'response_' . str_slug($url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment