# Introduction

I recently had an issue where I was running out of space in one of my Digital Ocean droplets due to an excess of file uploads in my application server.

So I decided it was a good idea to move all of my static media assets to a cloud storage service such as AWS S3 / Digital Ocean Spaces.

Laravel provides a very fluent filesystem abstraction (opens new window) that allows us to interact with a variety of filesystem drivers using a single API.

# Snippet

Here's a simple reusable function I came up with:

use Illuminate\Support\Facades\Storage;
function copyAllAssetsFromDiskToDisk($fromDisk, $toDisk) {
    $allFilePaths = Storage::disk($fromDisk)->allFiles('/');
    foreach ($allFilePaths as $filePath) {
        $file = Storage::disk($fromDisk)->get($filePath);
        $moved = Storage::disk($toDisk)->put($filePath, $file, 'public');
        // can optionally delete the file after it has been moved
        if ($moved) {
          Storage::disk($fromDisk)->delete($filePath);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# Explanation

  1. On line 5, we use the Storage facade and the allFiles() method to retrieve and store a list of all the files from the root of our $fromDisk disk.
  2. On lines 7-10
    1. On line 7, we loop through all the paths stored in our $allFilePaths array
    2. On line 8, we retrieve the contents of the file within the loop and store it in an array $file
    3. on line 10, we reference the $toDisk disk and use the put() method to store the contents of a file to its disk and give it a public visibility.
      • The put() method has 3 arguments, the path where we want to store the file, the contents of the file and the visibility of the file.
  3. On lines 13 - 15, we check if the file has been moved to the $toDisk and if so, we delete it from our $fromDisk.