Home > Back-end >  How to Read Private Files on Google Cloud Storage
How to Read Private Files on Google Cloud Storage

Time:09-16

I want to create a media storage apps, that allows user to upload and view their media on my platform. I use laravel to create it. I was successfully upload it to google cloud storage with private file attribute, and save the file name to my database.

My question is, how to access it directly from the laravel, and show it as image or video, currently I have cide.json file as a key, but I never get detail explaination how to use it.

CodePudding user response:

Okay, If I imagine your table structure, it might be like

id   user_id   file_location

You can build an api like

Route::get('users/{id}/files', FolderName\ControllerName@ControllerFunction)

Now you can fetch your user media files by passing the id or you can modify your controller to fetchAll the user media files depending upon your idea.

Brief explanation:

Add this route in Routes.php files in your laravel project

Route::get('users/{id}/files', User\UserApiController@fetchUserMediaFiles);

Create a new controller which manages the flow the request to service function

class UserApiController {

   public $userService;

   public function __construct(UserService $userService) {

        $this->userService = $userService;

   }

   public function fetchUserMediaFiles($id) {
     
         $userMediaFiles = $this->userService->fetchUserMediaFiles($id);

         return $this->done(null, [
             'userMediafiles' => $userMediaFiles
         ]); 

   }

}

Create a new service which handles the incoming request from Controller and sends it to repository

class UserService {

   private $userRepository;

   public function __construct(UserRepository $userRepository) {

       $this->userRepository= $userRepository;

   }

   public function fetchUserMediaFiles($id) {
    
      return $this->userRepository->fetchUserMediaFiles($id);

   }
}

Create new repository which would take the request from userService class and returns you the data by fetching from your db

class UserRepository {

public function fetchUserMediaFiles($id) {

    $userMediaFilesTable = UserMediaFiles::$TABLE_NAME;

    $model  = UserMediaFiles::with([])
                ->where("$userMediaFilesTable.user_id", $id);
    
    $model = $model->select(["$userMediaFilesTable.user_id", "$userMediaFilesTable.file_location"])
                    ->get();

    return $model;

    }
}

Now let's try to hit the api with a dummy get request

http://xxxxxxxx/api/users/1/files

Your response would be like

{
"userMediafiles": [
    {
        "user_id": 1,
        "file_location": "https://xxxxx.com/file",
    }
   
]

}

This is how you do in the laravel. Hope this explanation helps.

  • Related