Sep 14, 2015
12
Level 1
Response content Cache
Hello,
I want to cache pages in Laravel 5.1 like this (https://laracasts.com/lessons/caching-essentials (L4)) This is my afterFilter:
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$key = $this->makeCachKey($request->url());
if(!Cache::has($key)){
return Cache::put($key,Response::getContentFunctionOrSomething(),60);
}
return $next($request);
}
protected function makeCachKey($url){
return 'route_'.Str::slug($url);
}
}
In L4 is is Response::getContent, what function it is in L5?
Level 27
@peitje Okay got it working and learned a few things on the way. Best way to go.
Here it is.
BeforeMiddleWare.php
<?php
namespace App\Http\Middleware;
use Closure;
use Cache;
use Illuminate\Support\Str;
class BeforeMiddleWare
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$key = $this->keygen($request->url());
if (Cache::has($key)) {
$content=Cache::get($key);
return response($content);
}
return $next($request);
}
protected function keygen($url)
{
return 'route_' . str_slug($url);
}
}
AfterMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Cache;
use Illuminate\Support\Str;
use Event;
class AfterMiddleWare
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$key = $this->keygen($request->url());
if (! Cache::has($key)) {
Cache::put($key, $response->getContent(), 1);
}
return $next($request);
}
protected function keygen($url)
{
return 'route_' . str_slug($url);
}
}
Kernel.php
protected $routeMiddleware = [
...
'cacheafter' => \App\Http\Middleware\AfterMiddleware::class,
'cachebefore' => \App\Http\Middleware\BeforeMiddleware::class,
...
];
It's working just fine.
ps. I had to make something like this for a project i start tomorrow. I guess it started a day early :P
3 likes
Please or to participate in this conversation.