skip to Main Content

I want to save images to a special directory, example – storage/private_files And show certain images to certain users after authorization. The user’s images will then have to be displayed in the IMG tag in the browser. Paths to files will be stored in the database in conjunction with the user. How to properly organize saving and serving images in Laravel 8.83.21?

2

Answers


  1. You might consider using the temporary url function. If the user has access, you can create a temporary url for him and give the user access. And since the temporary url is expired, it cannot share the url with other users. This is the best way to handle file permissions:

    $url = Storage::temporaryUrl(
        'file.jpg', now()->addMinutes(5)
    );
    
    Login or Signup to reply.
  2. Well, there’s a plenty of way to do it (middleware, policies, user_permissions, …).

    What I would suggest (I don’t know what your model calls or the structure of your code, but when you get the idea apply it on yours):

    • Add new disk in config/filesystems.php
    'disks' => [
        'private' => [
            'driver' => 'local',
            'root' => storage_path('app/private_files'),
            'visibility' => 'private',
            'throw' => true,
        ],
    ],
    
    • To Save your file:

    $file->storeAs("uploads", "image_x.jpg", "private"); Or using Storage Facade

    • If file is downloadable for certain user (using Policies)

    Example of working with Policies

    class FilePolicy
    {
        public function download(User $user, FileModel $file): bool
        {
            return $user->isAdmin();
            //OR
            return $user->hasAccessTo($file); // assuming you have that function  
    
        }
    
        public function show(User $user, FileModel $file): bool
        {
            return $user->isAdmin();
            //OR
            return $user->hasAccessTo($file); // assuming you have that function  
    
        }
    }
    
    // XController.php
    
    public function download(FileModel $file): void
     {
        if ($request->user()->cannot('download', FileModel)) {
            abort(403);
        }
    
        return Storage::response($file->filename);
    }
    
    
    @can('show', $file) // similar for download
        <!-- The current user can see the file... -->
    @endcan
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search