如何在VerifyCsrfToken.php中解决" ErrorException"在Laravel

时间:2015-04-08 11:59:38

标签: php caching laravel middleware

这是我的方法:

我运行以下 PHP Artisan 命令:

php artisan make:middleware AfterCacheMiddleware

php artisan make:middleware BeforeCacheMiddleware

然后,我更新了我新创建的中间件( AfterCacheMiddleware BeforeCacheMiddleware ),如下所示:

AfterCacheMiddleware

class AfterCacheMiddleware  {

    /**
     * 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 $response;       
    }

    protected function keygen( $url )
    {
        return 'route_' . Str::slug( $url );
    }
}

BeforeCacheMiddleware

namespace App\Http\Middleware;

use Closure;
use Cache;
use Str;

class BeforeCacheMiddleware {

    /**
     * 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 ) ) return Cache::get( $key );

        return $next($request);
    }

    protected function keygen( $url )
    {
        return 'route_' . Str::slug( $url );
    }
}

此外,我已在 app/Http/Kernel.php

中注册了两个中间件
'App\Http\Middleware\AfterCacheMiddleware',
'App\Http\Middleware\BeforeCacheMiddleware',

'cacheafter' => 'App\Http\Middleware\AfterCacheMiddleware',
'cachebefore' => 'App\Http\Middleware\BeforeCacheMiddleware',

以下是我的路线:

Route::get('middle', ['middleware' => 'cachebefore','cacheafter', function()
{
    echo "success";
}]);

在首页加载时,一切正常(因为页面未缓存)

在后续访问中,我收到此错误: ErrorException in VerifyCsrfToken.php line 76: Trying to get property of non-object

我认为错误来自这一行:

if( Cache::has( $key ) ) return Cache::get( $key );

但我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

无需添加所有这些东西。如果你想更新标题信息,这些都很好。

在你的beforecacheiddleware中:

private

按照@Den

的建议更改上述代码
if( Cache::has( $key ) ) return Cache::get( $key );

这会奏效。如果您有任何问题,请退回。