Search code examples
phplaravellaravel-5laravel-storage

Get / Read laravel 5.8 Storage non public Folder files to View?


Try to access 'storage/app/folder1/a.png' from my view

enter image description here

public function viewStorageFiles()
{
    $fileFullPath = Storage::disk('local')->path('folder1/a.png');
    $fileUrl = Storage::disk('local')->url('app/folder1/a.png');
    $storage_path = storage_path('app/folder1/a.png');

    return view('email.fileDownload')->with([
        'fileFullPath' => $fileFullPath,
        'fileUrl' => $fileUrl,
        'storage_path' => $storage_path,
        ]);
}

In view : email.fileDownload

<div>
    <p>  asset($fileUrl) ==> {{asset($fileUrl)}}</p>
    <img src="{{asset($fileUrl)}}"/>
</div>
<div>
    <p>  url($fileUrl) ==> {{url($fileUrl)}}</p>
    <img src="{{url($fileUrl)}}"/>
</div>
<div>
    <p>  storage_path($fileUrl) ==> {{storage_path($fileUrl)}}</p>
    <img src="{{storage_path($fileUrl)}}"/>
</div>

the result is : enter image description here


Solution

  • There could be many answers to this!

    You could create a symbolic link from "public/storage" to "storage/app/public" using the following command:

    php artisan storage:link
    

    Above command will map your storage/app/public directory to public directory.

    Now let's consider you have user1.jpg and user2.jpg files in your storage/app/public directory, you can access them in the following way:

    http://your-domain.com/storage/user1.jpg
    http://your-domain.com/storage/user2.jpg
    

    * Updated my answer based on your comment: *

    You can return a file response from a route that is protected by some middleware!

    For example - following route returns file response from storage/app/uploads directory that is not accessible publicly:

    Route::get('storage/{file}', function ($file) {
        $path = storage_path('app' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $file);
        return response()->file($path);
    });
    

    You could secure above route in anyway and use it in your views..

    I hope that helped..