如何使用laravel 5跳过某些路线上的视图缓存?

I have route cache enable on my laravel 5 project. I'd like to skip the caching on particular routes views.

Then I found this post on internet:

https://laravel-tricks.com/tricks/invalidate-browser-cache-route-middleware

It's quite old so I adapted like the following:

Added in : Http/Kernel.php

protected $routeMiddleware = [
....
 'nohttp-cache' => NoHttpCache::class,
....
];

Created class in : Http/Middleware/NoHttpCache.php

namespace App\Http\Middleware;
use Closure;
//use Illuminate\Http\Response;
//use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class NoHttpCache  {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // This step is only needed if you are returning
        // a view in your Controller or elsewhere, because
        // when returning a view `$next($request)` returns
        // a View object, not a Response object, so we need
        // to wrap the View back in a Response.
//        if ( ! $response instanceof SymfonyResponse)
//        {
//            $response = new Response($response);
//        }

        /**
         * @var  $headers  \Symfony\Component\HttpFoundation\HeaderBag
         */
        $response->header('Pragma', 'no-cache');
        $response->header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
        $response->header('Cache-Control', 'no-cache, must-revalidate, no-store, max-age=0, private');

        return $response;
    }
}

I think there's no reason in Laravel 5 to wrap $response in Response. Then by simply adding browser cache "invalidation" directives....

It seems to work on a test route adding the middleware like:

in code/routes/web.php

 ....
 Route::get('/', 'MyController@index')->name('test')->middleware('nohttp-cache');
 ....

Now question are...

  • is this the right approach to skip caching on certain routes when route cache is enable globally?
  • Do you see any major issue on the middleware found?

You can use Laravel Page cache plugin by Joseph Silber designed to cache HTTP GET responses for fast page load.

Here is a link. Hope this help.

https://github.com/JosephSilber/page-cache