novichun's avatar

Laravel deny acces to storage public folder

Hello Guys!

I need some help with access of the storage public folder. I have a file upload system and the files stores in my storage/public/$user->id/ folder. Every users has an own folder for their files. In my show blade file i display their own files by an i frame:

<iframe 
    width="560"
    height="315"
    src="{{ URL::asset($file->file_path) }}" style="margin:auto"></iframe>

It's work totally fine but i dont want to can reach these files directly in the url like:

http://127.0.0.1:8000/storage/14/1639564147_file-example_PDF_500_kB.pdf

How can i solve this?

Thank you for your reply!

0 likes
1 reply
aschmelyun's avatar

Your best bet is to store the files not in the public folder, nothing should be stored there that you don't want anyone to access.

So instead, store them in something like storage/users/$user->id and then create a route that grabs the file and initializes a download only if the user is the one authenticated:

Route::get('/storage/users/{user}', function(Request $request, User $user) {
    if ($request->user()->id === $user->id) {
		$file = getFile(); // or however you'd want to retrieve the file
        return Storage::download('storage/users/' . $user->id . '/' . $file->file_path);
    }
    return abort(404);
}

Please or to participate in this conversation.