Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel change filesystem disks path on run time

I am aware of the filesystems.php to create disks and I'm currently using it, having ~~ 20 disks configured.

I have a new problem with these, I'm currently trying to prefix to every disk, a string. The problem is that the paths are being saved when the php artisan config:cache is run but I need to change them on run time, as n example, for User Sergio it would need to append Sergio/ to the following disk for example:

//filesystems.php
'random' => [
   'driver' => 'local',
   'root' => storage_path('app/random'),
],

Then

Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();
//outputs /var/www/html/project/storage/app/random

and the goal is setting configurations in for example the middleware i'm currently setting the tentant database already like this

//Middleware
Config::set('database.connections.tenant.database', "Sergio");
DB::reconnect('tenant');

I can currently set the paths correctly with

Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

But i'm worried since that if before that line I try to reach to the path, the storage saves the initial path in memory instead of re-fetching it after it is altered.

For example. doing this without any middleware.

$fullPath1 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

$fullPath2 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

What was intended to happen is that $fullPath1 would output the initial path which is /var/www/html/project/storage/app/random and then $fullPath2 would output /var/www/html/project/storage/app/Sergio/random

Is there any way of letting the Storage know that I've changed the disks local paths?

like image 851
Sérgio Reis Avatar asked Mar 21 '18 22:03

Sérgio Reis


1 Answers

How about adding a new config instead of updating the already loaded one, something like this:

private function addNewDisk(string $diskName) 
{
      config(['filesystems.disk.' . $diskName => [
          'driver' => 'local',
          'root' => storage_path('app/' . $diskName),
      ]]);
}

and prior to using the Storage facade, call above method that way the config will be updated and when you use new disk, it will try to resolve again based on updated config.

{
....
    $this->addNewDisk('new_random');
    Storage::disk('new_random')->get('abc.txt'); // or any another method
...

}
like image 186
gk. Avatar answered Oct 16 '22 05:10

gk.