1 year ago

Proper way to store public files

Posted 1 year ago by Demers94


I'm trying to store an image uploaded by the user in the public folder so that it can be viewed by anyone, and save the path on the Article model.

Here is the code that I tried using first :

$path = request()->file('file')->store('public/articles');

This places the image in the /storage/app/public/articles folder as I expected, but the problem is that the path it returns is equal to public/articles/ABC123.png. After I created the symbolic link to my public folder, I can't retrieve the file by using the assets() method because the path is incorrect. It tries to find the file in /public/articles, but with the symlink it's in /storage/articles instead.

I now use this instead :

$path = request()->file('file')->store('public/articles');
$path = str_replace('public', '/storage', $path);

If I do the above then I get the correct path, /storage/articles/ABC123.png and I can now use this to display the image.

Is this really the proper way to do things? It seems a bit weird to have to use str_replace() just to get a valid path. Is there a better way to achieve this?

Thanks for the help

Please sign in or create an account to participate in this conversation.