Easy-guide to integrate Laravel Application with Digital Ocean Spaces.

Fact Nº 1 — ► Amazon S3 is compatible with Laravel

Fact Nº 2 — ► Digital Ocean Spaces is compatible with Amazon S3

Transitive property — ► Digital Ocean Spaces is compatible with Laravel!


Step-by-step Guide to Integrate Larvel with DigitalOcean Spaces

Configuring Laravel

  1. Install via Composer Filesystem Adapter for AWS SDK V3
    composer require league/flysystem-aws-s3-v3
  2. Add the following disk to the array located in Config/filesystems.php
do_spaces' => [     
 'driver' => 's3',     
 'key' => env('DO_SPACES_KEY'),     
 'secret' => env('DO_SPACES_SECRET'),     
 'endpoint' => env('DO_SPACES_ENDPOINT'),     
 'region' => env('DO_SPACES_REGION'),     
 'bucket' => env('DO_SPACES_BUCKET'),
 'folder' => env('DO_SPACES_FOLDER'), 
],

3.   Add the following variables to your .env file

DO_SPACES_KEY=
DO_SPACES_SECRET= 
DO_SPACES_ENDPOINT=sfo2.digitaloceanspaces.com
DO_SPACES_REGION=SFO2
DO_SPACES_BUCKET=NAME_OF_YOUR_SPACE
DO_SPACES_FOLDER=

At this point, the setup should be ready. Now we will create two functions in a controller to upload and get files in Laravel Digital Ocean Spaces.

Upload image to disk:

After using the 'upload' field (Link), you will have to create a mutator on your model, where:

$attribute_name: name of the model's attribute
$disk: name of the disk configured before
$destination_path: name of the folder you want to store the files in Digital Ocean Space

public function setFileAttribute($value)
{
    $attribute_name = "file";
    $disk = "do_spaces";
    $destination_path = config("filesystems.disks.do_spaces.folder");
    $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}

Get image from disk:

public function getFile($id){
    $document = Document::where('id','=', $id)->firstOrFail();
    $file = Storage::disk('do_spaces')->get($document->file);
    $mimetype = \GuzzleHttp\Psr7\mimetype_from_filename($document->file);
    $headers = [
        'Content-Type' => $mimetype,
    ];
    return response($file, 200, $headers);
}

Advantages of Using Laravel Storage

As you may know, it is always a good idea to store your resources in the cloud, so go ahead and start the integration :)

Some of the advantages of Laravel Storage are:

  • Low cost
  • Availability
  • Easy to manage
  • Security
  • Scalability on-demand
  • Regular backups