Johnny
Johnny

Reputation: 301

Laravel create storage folder subfolders

In my Laravel storage folder, I have subfolders, such as users or admins. Is there something like a seeder for storage folders? Because I need to make sure that users exists when saving files to it (without checking if the folder actually exists), and furthermore I don't want to create these folders manually pulling from Git and deploying.

Upvotes: 2

Views: 4838

Answers (1)

Techno
Techno

Reputation: 1706

I believe I might have an interesting piece of code for you:

    /**
     * Generate directory structure
     * @param $basePath, path where all directories will be created in
     * @param $relativePath, recursive array in structure of directories
     * @param $permission, permission code to apply to folders
     */
    function generateDirectories($basePath, $relativePath, $permission)
    {
        //If array, unfold it
        if(is_array($relativePath))
        {
            foreach($relativePath as $key => $path)
            {
                //If key is not numeric, add it to foldername, else empty
                $folderName = is_numeric($key) ? '' : '\\' . $key;
                $this->generateDirectories($basePath . $folderName, $path, $permission);
            }
        }
        //Else handle it
        else
        {
            try
            {
                $this->fileSystem->makeDirectory($basePath . '\\' . $relativePath, $permission, true);
                $this->log('Successfully made directory: ' . $basePath . '\\' . $relativePath, 0);
            }
            catch(\Exception $ex)
            {
                //Do your logging or whatever
            }
        }
    }

Basically feed it an array like this:

[
    $moduleName => [
      'src' => [
        'Commands',
        'Contracts',
        'Controllers',
        'Models',
        'Providers',
        'DataTables',
        'Routes',
        'Migrations',
        'Resources' => [
            'Views',
            'Lang'
        ],
        'Assets' => [
            'js',
            'css'
        ],
    ],
]

And it starts building your folder structure.

Hope it helps :)

Upvotes: 2

Related Questions