fbpx

Make Laravel S3 Uploads Either Public or Private

You can either make ALL uploaded files in laravel public or private OR you can switch between either public or private. If you want to make all uploaded files public, set the config/filesystem.php files s3 array to the below values (replacing the AWS keys with your own)

AWS S3 Array in config/filesystems.php

's3' => [
            'driver' => 's3',
            'key' => 'your-key',
            'secret' => 'your-s3-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
            'visibility' => 'public',
        ],

You can remove the visibility key to set all uploaded files to s3 to private.

Switching Between Public and Private Uploads in Laravel

But if you don’t want all files that you upload to S3 to be public or private, start off by removing the visibility key from the s3 array in your config/filesystems.php file. 

AWS S3 Array in config/filesystems.php file

's3' => [
            'driver' => 's3',
            'key' => 'your-key',
            'secret' => 'your-s3-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

Then, use the commands below. This allows you to programmatically switch between whether you want a file to be public or private.

Set Upload to Public:

// Set file upload to public
$path = Storage::disk('s3')->put('directory_name/'.$user->id, $request->file('file_name'), 'public');

Set Upload to Private:

// Set file upload to private
$path = Storage::disk('s3')->put('directory_name/'.$user->id, $request->file('file_name'));

Leave a Reply

Your email address will not be published. Required fields are marked *