LoginSignup
8
10

More than 5 years have passed since last update.

Laravel5でレスポンスヘッダの'Cache-Control:no-cache'をどうにかしたい時のためのミドルウェア

Posted at

laravel5では特に設定を行わないとレスポンスヘッダに以下の値がセットされる

Cache-Control:no-cache

例えばこの状態だとブラウザキャッシュをしてくれなくなるので
ブラウザキャッシュが可能なコンテンツであればこの設定を変えてしまって良いはず

ミドルウェア作成

そんな訳でミドルウェアを作成する。
名前は何でも良いけどここではAllowCache.phpとする。
[アプリ]/app/Http/Middleware/以下にソースを作成。
今回はno-cacheをpublicに変えてみる

AllowCache.php
<?php

/**
 * リクエストヘッダを修正
 *
 * @copyright Copyright (c) 2015 All About, Inc.
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class AllowCache implements Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  Request $request
     * @param  Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (!$response->isRedirect()) {
            $response->header('Cache-Control', 'public');
        }

        return $response;
    }
}

ミドルウェアを登録

[アプリ]/app/Http/Kernel.php/以下にミドルウェアを登録
追記場所はとりあえず末尾に。

Kernel.php
protected $middleware = [
    ...,
    ...,
    ...,
    ...,
    'App\Http\Middleware\AllowCache',
];
8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10