Laravel file 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.
https://github.com/thephpleague/flysystem

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 are included in the configuration file. So, 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.

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

The Public Disk
The public disk is intended 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.

To create the symbolic link, you may use the storage:link Artisan command:
php artisan storage:link
Of course, once a file has been stored and the symbolic link has been created, you can create a URL to the files using the asset helper:

echo asset(‘storage/file.txt’);

The Local Driver
When using the local driver, 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:

Storage::disk(‘local’)->put(‘file.txt’, ‘Contents’);

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

SFTP: league/flysystem-sftp ~1.0
Amazon S3: league/flysystem-aws-s3-v3 ~1.0
Rackspace: league/flysystem-rackspace ~1.0
An absolute must for performance is to use a cached adapter. You will need an additional package for this:

CachedAdapter: league/flysystem-cached-adapter ~1.0

S3 Driver Configuration
The S3 driver configuration information is located in your config/filesystems.php configuration file. This file contains an example configuration array for an S3 driver. You are free to modify this array with your own S3 configuration and credentials. For convenience, these environment variables match the naming convention used by the AWS CLI.

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:

'ftp' => [
    'driver'   => 'ftp',
    'host'     => 'ftp.example.com',
    'username' => 'your-username',
    'password' => 'your-password',

    // Optional FTP Settings...
    // 'port'     => 21,
    // 'root'     => '',
    // 'passive'  => true,
    // 'ssl'      => true,
    // 'timeout'  => 30,
],

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

'sftp' => [
    'driver' => 'sftp',
    'host' => 'example.com',
    'username' => 'your-username',
    'password' => 'your-password',

    // Settings for SSH key based authentication...
    // 'privateKey' => '/path/to/privateKey',
    // 'password' => 'encryption-password',

    // Optional SFTP Settings...
    // 'port' => 22,
    // 'root' => '',
    // 'timeout' => 30,
],

Caching
To enable caching for a given disk, you may add a cache directive to the disk’s configuration options. The cache option should be an array of caching options containing the disk name, the expire time in seconds, and the cache prefix:

's3' => [
    'driver' => 's3',

    // Other Disk Options...

    'cache' => [
        'store' => 'memcached',
        'expire' => 600,
        'prefix' => 'cache-prefix',
    ],
],

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:

use Illuminate\Support\Facades\Storage;

Storage::put('avatars/1', $fileContents);
Storage::disk('s3')->put('avatars/1', $fileContents);

Retrieving Files
The get method may be used to retrieve the contents of a file. The raw string contents of the file will be returned by the method. Remember, all file paths should be specified relative to the “root” location configured for the disk:
$contents = Storage::get(‘file.jpg’);
The exists method may be used to determine if a file exists on the disk:
$exists = Storage::disk(‘s3’)->exists(‘file.jpg’);

Downloading Files
The download method may be used to generate a response that forces the user’s browser to download the file at the given path. The download method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

Temporary URLs
For files stored using the s3 or rackspace driver, you may create a temporary URL to a given file using the temporaryUrl method. This methods accepts a path and a DateTime instance specifying when the URL should expire:

$url = Storage::temporaryUrl(
‘file.jpg’, now()->addMinutes(5)
);

Local URL Host Customization
If you would like to pre-define the host for files stored on a disk using the local driver, you may add a url option to the disk’s configuration array:

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],

File Metadata
In addition to reading and writing files, Laravel can also provide information about the files themselves. For example, the size method may be used to get the size of the file in bytes:

use Illuminate\Support\Facades\Storage;

$size = Storage::size(‘file.jpg’);
The lastModified method returns the UNIX timestamp of the last time the file was modified:

$time = Storage::lastModified(‘file.jpg’);

storing Files
The put method may be used to store raw file contents on a 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:

use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents);
Storage::put('file.jpg', $resource);

Automatic Streaming
If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the putFile or putFileAs method. This method accepts either a Illuminate\Http\File or Illuminate\Http\UploadedFile instance and will automatically stream the file to your desired location:

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

// Automatically generate a unique ID for file name...
Storage::putFile('photos', new File('/path/to/photo'));

// Manually specify a file name...
Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

There are a few important things to note about the putFile method. Note that we only specified a directory name, not a file name. By default, the putFile method will generate a unique ID to serve as the file name. The file’s extension will be determined by examining the file’s MIME type. The path to the file will be returned by the putFile method so you can store the path, including the generated file name, in your database.

The putFile and putFileAs methods also accept an argument to specify the “visibility” of the stored file. This is particularly useful if you are storing the file on a cloud disk such as S3 and would like the file to be publicly accessible:
Storage::putFile(‘photos’, new File(‘/path/to/photo’), ‘public’);

Prepending & Appending To Files
The prepend and append methods allow you to write to the beginning or end of a file:

Storage::prepend(‘file.log’, ‘Prepended Text’);

Storage::append(‘file.log’, ‘Appended Text’);
Copying & Moving Files
The copy method may be used to copy an existing file to a new location on the disk, while the move method may be used to rename or move an existing file to a new location:

Storage::copy(‘old/file.jpg’, ‘new/file.jpg’);
Storage::move(‘old/file.jpg’, ‘new/file.jpg’);

File Uploads
In web applications, one of the most common use-cases for storing files is storing user uploaded files such as profile pictures, photos, and documents. Laravel makes it very easy to store uploaded files using the store method on an uploaded file instance. Call the store method with the path at which you wish to store the uploaded file:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserAvatarController extends Controller
{
    /**
     * Update the avatar for the user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        $path = $request->file('avatar')->store('avatars');

        return $path;
    }
}

There are a few important things to note about this example. Note that we only specified a directory name, not a file name. By default, the store method will generate a unique ID to serve as the file name. The file’s extension will be determined by examining the file’s MIME type. The path to the file will be returned by the store method so you can store the path, including the generated file name, in your database.

You may also call the putFile method on the Storage facade to perform the same file manipulation as the example above:

$path = Storage::putFile(‘avatars’, $request->file(‘avatar’));
Specifying A File Name
If you would not like a file name to be automatically assigned to your stored file, you may use the storeAs method, which receives the path, the file name, and the (optional) disk as its arguments:

$path = $request->file(‘avatar’)->storeAs(
‘avatars’, $request->user()->id
);
Of course, you may also use the putFileAs method on the Storage facade, which will perform the same file manipulation as the example above:

$path = Storage::putFileAs(
‘avatars’, $request->file(‘avatar’), $request->user()->id
);

File Visibility
In Laravel’s Flysystem integration, “visibility” is an abstraction of file permissions across multiple platforms. Files may either be declared public or private. When a file is declared public, you are indicating that the file should generally be accessible to others. For example, when using the S3 driver, you may retrieve URLs for public files.

You can set the visibility when setting the file via the put method:

use Illuminate\Support\Facades\Storage;

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:

use Illuminate\Support\Facades\Storage;

Storage::delete('file.jpg');

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