laravellaravel-5.5

storePubliclyAs not saving in public folder


I don't know if I have misunderstood something, but I call the following method during a file upload:

$cover->storePubliclyAs($coverAsset->dir, $coverAsset->preview_name);

$coverAsset->dir returns businesses/2 and $coverAsset->preview_name returns a hashed file name.

After doing the upload I end up with a file at: storage/app/businesses/1/pre-AxDMVlSN.jpeg

I am confused, why isn't the file saved in storage/app/public/businesses/...? I would expect the 'publicly' part to put it in the public folder of the storage directory structure provided by Laravel.

I looked at my filesystems configuration:

'disks' => [

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

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

It feels like the local disk is used instead of the public disk? How do I find out which one is used by UploadedFile->storePubliclyAs method?


Solution

  • The function storePubliclyAs based from this: https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/UploadedFile.php#L61

    It just sets the file's visibility into public, contrary to what you assumed that it will move/store the file into the public folder.

    To actually select a disk where you want it to be stored. Just use the third optional parameter of the storePubliclyAs which is the $options parameter.

    Note that, if you didn't choose a disk (by passing an $options parameter), Laravel will use the default selected disk based from your filesystems.php config file.

    According to what I've read about the code, you can just pass the disk name as the third parameter.

    So instead of this:

    $cover->storePubliclyAs($coverAsset->dir, $coverAsset->preview_name);

    Use this (we'll use public since you want to store it in the disk named public):

    $cover->storePubliclyAs($coverAsset->dir, $coverAsset->preview_name, 'public');


    Furthermore, take a look at Laravel's default filesystems.php: https://github.com/laravel/laravel/blob/master/config/filesystems.php#L16

    That line looks for a FILESYSTEM_DRIVER entry in the .env file, however if it didn't find one, it will use the second parameter; by default which is local.

    I think you're config is defaulting into the local disk. What you may try to do is either to append FILESYSTEM_DRIVER=public in your .env file or change the second parameter in the filesystems.php to public.

    Please let me know if there are any errors, since I haven't tried anything of this, I've just read the code.

    If want to trace the code yourself, you can look it up here: https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/UploadedFile.php