May 28, 2016

Adding Laravel's Storage facade into Lumen

Nick Silvestro

All posts

UPDATED (2016-09-30) - this post was originally written for Lumen 5.2, and has now been updated with the correct code for Lumen 5.3 also - the only change is at the very end, but please read the full post anyway. Thanks to Kevin for his input!


Since it was 'taken out' in 5.2, putting the Storage facade back into Lumen proved fairly difficult if you enjoy quickly Googling stuff and randomly copy/pasting Laracast or StackOverflow answers into your codebase. This is mostly to do with the fact that the majority of the answers out there for getting it working are pre-5.2, when there were still remnants of it in the codebase.

Anyway, down to the nitty gritty.

Firstly, determine what drivers you want installed - for my project, I just want S3, so I'll add league/flysystem-aws-s3-v3 but if you just want local, you can just add league/flysystem

$ composer require league/flysystem-aws-s3-v3 ~1.0

Secondly, make a config folder, grab a copy of the contents of https://raw.githubusercontent.com/laravel/laravel/master/config/filesystems.php and throw it in there:

$ mkdir config
$ cd config
$ wget https://raw.githubusercontent.com/laravel/laravel/master/config/filesystems.php

Edit the values in the filesystems.php file accordingly - I changed the static values for env('S3_KEY') values so I could keep all my config inside .env like a good Lumen app.

Now, we need to enable a bunch of stuff inside bootstrap/app.php, so open that in your favourite editor.

Start by enabling Facades if you haven't already, by uncommenting // $app->withFacades();, then immediately above that line, add the following:

$app->configure('filesystems');

This will ensure that our new filesystems.php config file is loaded before anything else.

Next, immediately below the withFacades call, add this to alias the Storage facade correctly:

class_alias('Illuminate\Support\Facades\Storage', 'Storage');  

Now, for Lumen 5.2, you need to add the following underneath the other singleton method calls in the Register Container Bindings section, making sure you use the right code for your Lumen version:

$app->singleton('filesystem', function ($app) {
    return $app->loadComponent(
        'filesystems',
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        'filesystem'
    );
});

If you're instead up to date and using Lumen 5.3, it's even easier. Nearer to the bottom, add this line into the Register Service Providers section:

$app->register(Illuminate\Filesystem\FilesystemServiceProvider::class);

That's it! Pending correct configuration, the Storage facade should now work as per the standard Laravel documentation.

Yay!