ZoltanParragi
ZoltanParragi

Reputation: 43

How to store and provide images without public access in Laravel?

I make an app with Laravel backend and React frontend and use token based authentication. Users and admin can upload files (eg. images), they are stored in the storage folder. I created this solution based on Laravel docs: https://laravel.com/docs/10.x/filesystem. I creatd sym links with 'php artisan storage:link'.

My problem is that uploaded files are publicly accessible via links. I'd like to protect these files, make them available only for users.

How can I ensure it?

I tried to put images in a different folder (eg.: uploads). I tried to access files with 'file($path)' but it only works with 'storage/images/1697829128.jpg' and not with 'uploads/images/1697829128.jpg'.

Upvotes: 1

Views: 713

Answers (1)

Md Mainul Islam
Md Mainul Islam

Reputation: 66

When you are create a folder under Storage without 'public' that will be not public in browser URL. so create an example folder outside the public directory to store your private files. Now, configure your Laravel application to use this new folder as the disk for private files. You can do this in here config/filesystems.php (Can change based on your preferences)

    'private' => [
    'driver' => 'local',
    'root' => storage_path('app/private'),
],

to provide access to these images, create a route and controller method that fetches and serves the images to authenticated users. In your controller, you can use the response()->download() method:

public function downloadFiles($filename)
{
    $path = storage_path("app/private/files/$filename");
return response()->download($path, $filename, ['Content-Type' => 'image/jpeg']);
}

Upvotes: 1

Related Questions