Search code examples
laravelamazon-web-servicesamazon-s3

Setting AWS S3 file permission to public after upload in Laravel


I am developing a web application. In my application, I am implementing file uploaded feature. I store the uploaded file in an AWS S3 bucket. I am uploading the file to the s3 bucket as follow.

 $photo_file_path = $request->file('image_file')->store(
            'images/artworks/gallery-images/'.uniqid(),  's3'
          );

The above code is working fine. The file is uploaded to S3. But the problem is I want the file to be public when it is uploaded to S3 so that the photo can be accessible from URL as well. I set both bucket policy and access control to public.

This is my bucket policy

{
    "Version": "2012-10-17",
    "Id": "Policy1234566788",
    "Statement": [
        {
            "Sid": "Stmt151234344545",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my-bucket"
        }
    ]
}

As you can see my bucket is now public for both access control and bucket policy.

enter image description here

But when I upload the file from Laravel, it is uploaded to the bucket, but the file is still hidden from the public. How can I change the file permission to public once the file is uploaded?


Solution

  • Laravel provides different methods to store the files.

    One of the easiest way is to use storePublicly():

    $photo_file_path = $request->file('image_file')->storePublicly(
            'images/artworks/gallery-images/'.uniqid()
          );