Search code examples
phplaravelfile-uploadlaravel-storage

Laravel get public url for file stored in storage public folder


On Windows I have Xampp. My application is in Anuglar and Laravel 8 I add files to folder public in storage folder. Configuration in filesystem.php:

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

In .env file:

APP_URL=http://localhost:8082/prftbx-crm-api/public

File in public folder:

 Directory of C:\xampp\htdocs\crm-api\storage\app\public

06/25/2021  11:01 AM    <DIR>          .
06/25/2021  11:01 AM    <DIR>          ..
04/26/2021  10:57 PM                14 .gitignore
06/25/2021  11:01 AM               510 381787c3ad1442cc882ee427e93af805.txt

In Laravel I return url using method:

$fileDTO->filePath = Storage::url($fileEntity->file_name);

And in view I have address:

/storage/381787c3ad1442cc882ee427e93af805.txt

When I type url in the browser:

http://localhost:8082/crm-api/public/storage/381787c3ad1442cc882ee427e93af805.txt

I get 404, file not found


Solution

  • First run following command

    php artisan storage:link
    

    then you can

    http://localhost:8082/storage/381787c3ad1442cc882ee427e93af805.txt
    

    keep app url as

    APP_URL=http://localhost:8082
    

    As document says

    The public disk included in your application's filesystems configuration file is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores its files in storage/app/public.

    To make these files accessible from the web, you should create a symbolic link from public/storage to storage/app/public. Utilizing this folder 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 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:

    Ref:https://laravel.com/docs/8.x/filesystem#the-public-disk