Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cobs's avatar
Level 1

Storage dependency injection

Hi,

I created a new local disk for my filesystem I have many controllers where I have to repeat the Storage::disk("shared") declaraton. however i would like to stay DRY.

So my idea was to inject the Filesystem instance and use it like this

public function index (SharedFilesystem $disk)
{
    return $disk->files('/');
}

But i can't find a good way to bind my SharedFilesystem in the Service Container. Do you have any idea ?

I still use laravel 5.4 for this project.

0 likes
7 replies
martinbean's avatar
Level 80

@cobs You can find the corresponding interface you need to type-hint for each facade here: https://laravel.com/docs/8.x/facades#facade-class-reference

For storage, you can either type-hint the manager (which gives you access to all disks) using Illuminate\Filesystem\FilesystemManager or an instance of the default driver by type-hinting Illuminate\Contracts\Filesystem\Filesystem.

If you want to inject a non-default disk into your controllers, then you’ll need to use the manager and then access the named disk via that:

class FooController extends Controller
{
    protected $disk;

    public function __construct(FilesystemManager $manager)
    {
        $this->disk = $manager->disk('shared');
    }
}

If you don’t want to have to specify the name of the disk then you’ll need to add a contextual binding to the container:

$this->app->when(FooController::class)
          ->needs(Filesystem::class)
          ->give(function () {
              return $this->app['filesystem']->driver('shared');
          });

However, you’ll just make your life easier if you just use the default disk.

1 like
Cobs's avatar
Level 1

Thanks, Indeed, contextual binding looks like what i want to do but registering each controller in the conditions is more painful than just specifying the disk. Thanks to you i think i can find a way to just type hint the dependencies with the right disk.

Cobs's avatar
Level 1

Maybe I miss something but i don't need a custom filesystem. The "local" driver works fine.

I want to use a non-default local filesystem without having to specify the name of the disk again & again. The point here is to avoid redundancy.

martinbean's avatar

@cobs But how is Laravel supposed to know if you want to use the default disk or your custom disk without you specifying it…?

Cobs's avatar
Level 1

My "shared" functionnality will have some complexity into it. (Storing metadata, trigger events, ACL) So i try keep my controller's actions seamless and don't spread the complexity accross multiple controllers & classes.

ideally, I want to specify the disk selection part only once, then use an injected facade to interact with the storage.

Please or to participate in this conversation.