Laraveldeep's avatar

Add/Update Cache Control Metadata on S3 Objects

Hi,

How to add/update "cache-control"meta data on S3 using filesystem? Documentation only mentions the metadata about size etc. https://laravel.com/docs/5.3/filesystem

Thanks!

0 likes
5 replies
DmytroOlefyrenko's avatar

To do it you need to get access to underlying object by using getDriver() and then you can pass additional meta data as third parameter to put function. See signature of that function:

/**
     * Create a file or update if exists.
     *
     * @param string $path     The path to the file.
     * @param string $contents The file contents.
     * @param array  $config   An optional configuration array.
     *
     * @return bool True on success, false on failure.
     */
    public function put($path, $contents, array $config = []);

So in you case this should look something like this:

Storage::disk('s3')->getDriver()->put(
    '/test.txt', 
    'test',
    [
        'CacheControl'  => 'max-age'
    ]
);

Yes, you need use CacheControl instead of Cache-Control :-)

2 likes
Laraveldeep's avatar

Will try this later and update.

For the mean time I have solved the issue using aws-cli to update the cache control for thousands of files already uploaded.

Planning to integrate this feature on CMS I am currently working on.

Thanks!

Robstar's avatar

I've only recently discovered that updating config/filesytems.php with meta options works:

's3' => [
    'driver' => 's3',
        'key' => env('AWS_KEY'),
        'secret' => env('AWS_SECRET'),
        'region' => env('AWS_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'options' => [
            'CacheControl' => 'max_age=31536000'
        ],
],
2 likes
Robstar's avatar

@Laraveldeep Have just noticed you said you need to do this for thousands of files. If that's the case use the aws-cli - it's quicker and cheaper than individual requests from your application.

Please or to participate in this conversation.