Add Sonic object storage to Laravel

Laravel logo

Laravel's S3 driver relies on the Flysystem S3 package and works with Sonic's S3-compatible API out of the box.

Install Flysystem

$ composer require league/flysystem-aws-s3-v3 "^3.0"

Open the .env file and change the filesystem disk value to S3:

Laravel version 9 and up:

FILESYSTEM_DISK=s3

Older versions:

FILESYSTEM_DRIVER=s3

When you create a Sonic storage zone, you have the option select the default Virtual-hosted style bucket or the deprecated path-style. Depending on which one you've chosen, proceed to add your Sonic storage credentials to the environment variables. You can find them in the "Storage & Hostnames" tab of your push (storage) CDN zone:

Virtual-hosted style buckets (Sonic default)

Add to your .env file:

AWS_ENDPOINT=https://s3.de01.sonic.r-cdn.com
AWS_ACCESS_KEY_ID=T8E3MEMSHG0FF
AWS_SECRET_ACCESS_KEY=TzVES59SODTDQcPDNUFBNzh
AWS_BUCKET=1001
AWS_USE_PATH_STYLE_ENDPOINT=false

Note that AWS_USE_PATH_STYLE_ENDPOINT is set to false in this example. Also note that the AWS_URL variable is not set as it will default to https://1001.s3.de01.sonic.r-cdn.com, which will be the URL where your bucket's content will be delivered from. This URL is automatically routed via Pushr's global edge network to cache and accelerate the delivery of all assests you store in Sonic.

Path-style buckets (deprecated)

Add to your .env file:

AWS_ENDPOINT=https://s3.de01.sonic.r-cdn.com
AWS_ACCESS_KEY_ID=T8E3MEMSHG0FF
AWS_SECRET_ACCESS_KEY=TzVES59SODTDQcPDNUFBNzh
AWS_BUCKET=1001
AWS_USE_PATH_STYLE_ENDPOINT=true
AWS_URL=https://123456.r-cdn.com

In this example, the URL from which your bucket's contents will be delivered is a unique CDN hostname created by Pushr. You will find it listed in the "Storage and Hostnames" tab of your storage zone. You would need to set this variable so that Laravel knows how to construct links to your files correctly.

Bucket policy

Sonic does not support editing of bucket policies. There is one default mixed access policy that applies to each bucket. It has the following characteristics:

• Unauthenticated requests can download files from the bucket url/CDN hostname via direct links.

• Only authenticated requests can write, list and tag objects. This behaviour is equivalent to disabling AWS's Block Public Access setting.

Custom hostnames (optional)

You can brand your CDN hostname (bucket URL) to provide a more unified and professional look to your app. Learn how to do this here and then update the AWS_URL variable in your .env file with the value of the newly created hostname.