Search code examples
phplaravellaravel-5laravel-facade

How to map private resource to public in Laravel?


I have been using the Storage facade to store user profile pictures and they are being saved inside the Storage folder in the project. The problem is that I cannot directly display these photos because of the permissions of the storage folder, I have read people mentioning mapping a private resource to a public one but I am unsure how to exactly do this.

For example here is a snippet of code I am using to save a photo upload

 if (Storage::disk('public')->has($usersname)) {
            Storage::delete($usersname. '.' . $ext);
        }
        Storage::disk('public')->put($filename, File::get($file));

But in the view I cannot directly display this now saved resource


Solution

  • You could use two different approaches:

    • #1: define a new disk for your storage that is linked to a directory inside the public folder. Something like public/profile_pics. All you need to do, then, is to use that disk while uploading profile pictures. This way, they will be accessible anywhere;
    • #2: if you don't want to expose your files directly, define a private disk for your profile pics, and then create a route (maybe /profile-pic/{userId}) that will serve a specific response with the image data and the right headers;

    EDIT: Laravel uses Flysystem for the storage. So, if you take a look to the API page of the project you can find the

    $mimetype = $filesystem->getMimetype('path/to/file.txt');
    

    example that can help you to get the right mimetype for the response you're going to build (in case you're implementing #2).

    Hope it helps :)