Filesystem / Cloud Storage

Introduction

Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.

Configuration

The filesystem configuration file is located at config/filesystems.php. Within this file you may configure all of your "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver is included in the configuration file. So, simply modify the configuration to reflect your storage preferences and credentials.

Of course, you may configure as many disks as you like, and may even have multiple disks that use the same driver.

The Public Disk

The public disk is meant for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public. To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public. This convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like Envoyer.

Of course, once a file has been stored and the symbolic link has been created, you can create an URL to the files using the asset helper:

  1. echo asset('storage/file.txt');

The Local Driver

When using the local driver, note that all file operations are relative to the root directory defined in your configuration file. By default, this value is set to the storage/app directory. Therefore, the following method would store a file in storage/app/file.txt:

  1. Storage::disk('local')->put('file.txt', 'Contents');

Other Driver Prerequisites

Before using the S3 or Rackspace drivers, you will need to install the appropriate package via Composer:

  • Amazon S3: league/flysystem-aws-s3-v3 ~1.0
  • Rackspace: league/flysystem-rackspace ~1.0

FTP Driver Configuration

Laravel's Flysystem integrations works great with FTP; however, a sample configuration is not included with the framework's default filesystems.php configuration file. If you need to configure a FTP filesystem, you may use the example configuration below:

  1. 'ftp' => [
  2. 'driver' => 'ftp',
  3. 'host' => 'ftp.example.com',
  4. 'username' => 'your-username',
  5. 'password' => 'your-password',
  6. // Optional FTP Settings...
  7. // 'port' => 21,
  8. // 'root' => '',
  9. // 'passive' => true,
  10. // 'ssl' => true,
  11. // 'timeout' => 30,
  12. ],

Rackspace Driver Configuration

Laravel's Flysystem integrations works great with Rackspace; however, a sample configuration is not included with the framework's default filesystems.php configuration file. If you need to configure a Rackspace filesystem, you may use the example configuration below:

  1. 'rackspace' => [
  2. 'driver' => 'rackspace',
  3. 'username' => 'your-username',
  4. 'key' => 'your-key',
  5. 'container' => 'your-container',
  6. 'endpoint' => 'https://identity.api.rackspacecloud.com/v2.0/',
  7. 'region' => 'IAD',
  8. 'url_type' => 'publicURL',
  9. ],

Basic Usage

Obtaining Disk Instances

The Storage facade may be used to interact with any of your configured disks. For example, you may use the put method on the facade to store an avatar on the default disk. If you call methods on the Storage facade without first calling the disk method, the method call will automatically be passed to the default disk:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Storage;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. class UserController extends Controller
  7. {
  8. /**
  9. * Update the avatar for the given user.
  10. *
  11. * @param Request $request
  12. * @param int $id
  13. * @return Response
  14. */
  15. public function updateAvatar(Request $request, $id)
  16. {
  17. $user = User::findOrFail($id);
  18. Storage::put(
  19. 'avatars/'.$user->id,
  20. file_get_contents($request->file('avatar')->getRealPath())
  21. );
  22. }
  23. }

When using multiple disks, you may access a particular disk using the disk method on the Storage facade. Of course, you may continue to chain methods to execute methods on the disk:

  1. $disk = Storage::disk('s3');
  2. $contents = Storage::disk('local')->get('file.jpg');

Retrieving Files

The get method may be used to retrieve the contents of a given file. The raw string contents of the file will be returned by the method:

  1. $contents = Storage::get('file.jpg');

The exists method may be used to determine if a given file exists on the disk:

  1. $exists = Storage::disk('s3')->exists('file.jpg');

File URLs

When using the local or s3 drivers, you may use the url method to get the URL for the given file. If you are using the local driver, this will typically just prepend /storage to the given path and return a relative URL to the file. If you are using the s3 driver, the fully qualified remote URL will be returned.

  1. $url = Storage::url('file1.jpg');

Note: When using the local driver, be sure to create a symbolic link at public/storage which points to the storage/app/public directory.

File Meta Information

The size method may be used to get the size of the file in bytes:

  1. $size = Storage::size('file1.jpg');

The lastModified method returns the UNIX timestamp of the last time the file was modified:

  1. $time = Storage::lastModified('file1.jpg');

Storing Files

The put method may be used to store a file on disk. You may also pass a PHP resource to the put method, which will use Flysystem's underlying stream support. Using streams is greatly recommended when dealing with large files:

  1. Storage::put('file.jpg', $contents);
  2. Storage::put('file.jpg', $resource);

The copy method may be used to copy an existing file to a new location on the disk:

  1. Storage::copy('old/file1.jpg', 'new/file1.jpg');

The move method may be used to rename or move an existing file to a new location:

  1. Storage::move('old/file1.jpg', 'new/file1.jpg');

Prepending / Appending To Files

The prepend and append methods allow you to easily insert content at the beginning or end of a file:

  1. Storage::prepend('file.log', 'Prepended Text');
  2. Storage::append('file.log', 'Appended Text');

File Visibility

File visibility can be retrieved and set via the getVisibility and setVisibility methods. Visibility is the abstraction of file permissions across multiple platforms:

  1. Storage::getVisibility('file.jpg');
  2. Storage::setVisibility('file.jpg', 'public');

Additionally, you can set the visibility when setting the file via the put method. The valid visibility values are public and private:

  1. Storage::put('file.jpg', $contents, 'public');

Deleting Files

The delete method accepts a single filename or an array of files to remove from the disk:

  1. Storage::delete('file.jpg');
  2. Storage::delete(['file1.jpg', 'file2.jpg']);

Directories

Get All Files Within A Directory

The files method returns an array of all of the files in a given directory. If you would like to retrieve a list of all files within a given directory including all sub-directories, you may use the allFiles method:

  1. $files = Storage::files($directory);
  2. $files = Storage::allFiles($directory);

Get All Directories Within A Directory

The directories method returns an array of all the directories within a given directory. Additionally, you may use the allDirectories method to get a list of all directories within a given directory and all of its sub-directories:

  1. $directories = Storage::directories($directory);
  2. // Recursive...
  3. $directories = Storage::allDirectories($directory);

Create A Directory

The makeDirectory method will create the given directory, including any needed sub-directories:

  1. Storage::makeDirectory($directory);

Delete A Directory

Finally, the deleteDirectory may be used to remove a directory, including all of its files, from the disk:

  1. Storage::deleteDirectory($directory);

Custom Filesystems

Laravel's Flysystem integration provides drivers for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application.

In order to set up the custom filesystem you will need to create a service provider such as DropboxServiceProvider. In the provider's boot method, you may use the Storage facade's extend method to define the custom driver:

  1. <?php
  2. namespace App\Providers;
  3. use Storage;
  4. use League\Flysystem\Filesystem;
  5. use Dropbox\Client as DropboxClient;
  6. use Illuminate\Support\ServiceProvider;
  7. use League\Flysystem\Dropbox\DropboxAdapter;
  8. class DropboxServiceProvider extends ServiceProvider
  9. {
  10. /**
  11. * Perform post-registration booting of services.
  12. *
  13. * @return void
  14. */
  15. public function boot()
  16. {
  17. Storage::extend('dropbox', function($app, $config) {
  18. $client = new DropboxClient(
  19. $config['accessToken'], $config['clientIdentifier']
  20. );
  21. return new Filesystem(new DropboxAdapter($client));
  22. });
  23. }
  24. /**
  25. * Register bindings in the container.
  26. *
  27. * @return void
  28. */
  29. public function register()
  30. {
  31. //
  32. }
  33. }

The first argument of the extend method is the name of the driver and the second is a Closure that receives the $app and $config variables. The resolver Closure must return an instance of League\Flysystem\Filesystem. The $config variable contains the values defined in config/filesystems.php for the specified disk.

Once you have created the service provider to register the extension, you may use the dropbox driver in your config/filesystem.php configuration file.