CodeAgent
CodeAgent

Reputation: 103

How to loop throught folders and subfolders and create using Laravel?

Hi need help in creating nested folders.

I currently have a folder called images and i would like to clone the folders and save it in a different folder call backup. and the backup will only happen when user clicks backup.

For example:

- Images
 - Car
    - A
      - A1
        - A1-1
      - A2
    - B
 - Van

How can i write the code so that it will create the folders?

Currently i have done this so how can i do it?

public function sync(Request $request)
{
    $arr = [];
    $folderToSync = $request->input('folderName');

    $originalPath = public_path($folderToSync);
    $newFolderPath = public_path('S3/'.$folderToSync);

    $this->createFolder($newFolderPath); // create the selected folder

    $directories = $this->getAllFolders($originalPath); // getting all folders under the original path

    $this->folder($directories, $newFolderPath, $originalPath);

    dd('end');
}

public function createFolder($path)
{
    if (!is_dir($path)) {
        @mkdir($path, 0777, true);
    }
}

public function folder($directories, $newFolderPath, $originalPath)
{
    foreach ($directories as $directory) {
        $newPath = $newFolderPath.'/'.$directory;
        $oriPath = $originalPath.'/'.$directory;

        $this->createFolder($newPath);
        $subFolders = $this->getAllFolders($oriPath);

        if ($subFolders) {
            $this->subfolder($subFolders, $newPath);
        }
    }
}

public function subfolder($directories, $path)
{
    foreach ($directories as $directory) {
        $this->createFolder($path.'/'.$directory);
    }
}

public function getAllFolders($path)
{
    return array_map('basename', \File::directories($path));
}

public function getAllFiles($path)
{
    return;
}

but its not creating the subfolders. How can i modify it ?

i would run the code every week and i want to check also which folder have been created and which have not been created. if the folder does not exist then create the folder.

Upvotes: 2

Views: 3552

Answers (1)

Adam Rodriguez
Adam Rodriguez

Reputation: 1856

I would have a look at the storage api from the Laravel documentation: https://laravel.com/docs/5.7/filesystem#directories

To acquire folders and subfolders:

// Recursive...
$directories = Storage::allDirectories($directory);

Creating a new directory:

Storage::makeDirectory($directory);

Storing files:

Storage::put('file.jpg', $contents);

Storage::put('file.jpg', $resource);

The put method will take either the file contents or a resource.

Don't forget to include the Storage facade:

use Illuminate\Support\Facades\Storage;

Upvotes: 2

Related Questions