Created
January 11, 2017 18:39
-
-
Save trouttdev/ec7fc48351641e9289a31404884221c8 to your computer and use it in GitHub Desktop.
Simple Laravel 5 response caching
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\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