Inject Storage in Laravel

How do you inject Storage in Laravel? I’ve noticed in my Google searches that all the examples I come across on how to use the various components of Laravel only show how to use Facades. But what if you want to use constructor injection?

If you would like to know how to inject the Storage Facade in Laravel, or more accurately, the FileSystem component, read on…

If you’re programming tests, you’ll come across cases where in order to test, you must inject. You don’t actually need to inject in the case of Storage, because the Facade has a “fake” method. However, what if you still want to so that you can remain consistent with the rest of your app?

It took me some serious searching to find the solution, but here it is:

<?php declare(strict_types = 1);

namespace App\Modules\Saver;

use Illuminate\Contracts\Filesystem\Factory as Filesystem;

class Saver
{
    /** @var Filesystem */
    private $storage;

    public function __construct(Filesystem $storage)
    {
        $this->storage = $storage;
    }

    /**
     * Save
     *
     * @param string $content
     */
    public function save(string $content): void
    {
        $this->storage->disk('local')->put('filename.txt', $content);
    }

Of course, you can override the disk name and filename dynamically if you need to. The test for this would look like:

    /** @test  */
    public function it_saves()
    {
        Storage::fake('local');

        /** @var Saver $saver */
        $saver = $this->app->make(Saver::class);
        $saver->save('some text');

        Storage::disk('local')->assertExists('filename.txt');
    }
inject storage in Laravel - passing test

You can still use the Storage facade in your test to make things simple.

If you’d like to see more of my blog posts, you can start at the home page.

If you like dogs, you may enjoy my YouTube channel BarooBoos.

I have been programming for over 20 years, most recently with Laravel. My goal is 100% test coverage wherever possible, and I’ve found that injection and mocking is necessary to do this in most cases. It’s interesting to see how differently you have to code in order to make testing possible. If you’re not testing your code, learn as much as you can about testing, then begin practicing. You’ll be surprised how much you’ll learn as you try to write tests and find you simply can’t because of the way your code is written.

Leave a Reply

Your email address will not be published. Required fields are marked *