How to create nested directory from array in php

- 1 answer


In laravel, I am trying to create the file using console. The file that I will be creating is a trait file. My situation is that, if I just write the name of the file, it gets created as desired. But when passed as a directory, it doesn't gets created.

The array can be dynamic. It is upto the user how much deep the directory should be.

Just for the example: I am taking 2 levels of directories.

My array is:

    [0] => 'RootTrait' // the root place of the trait folder
    [1] => 'Level-1' // Directory inside the trait folder
    [2] => 'Level-2' // Directory inside the Level-1 folder
    [3] => 'file.php' // The file that will be created inside Level 2 folder

What should I do to achieve this ?

The code that I have tried so far is:

 * Process the creation of trait file.
 * @param  string $traitName
 * @param  \Illuminate\Filesystem\Filesystem $file
 * @param  string $nameSpace
 * @return bool
 public function processTraitFile($traitName, Filesystem $file, $nameSpace = 'App')
     $traitFileName = $file->get('app/stubs/Trait.stub');

     $newTraitFile = str_replace(['TraitName', 'App'], [$traitName, $nameSpace], $traitFileName);

     if (! file_exists("app/Http/Traits/{$traitName}")) {
         $traitFolders = explode('/', $traitName);
         $lastElement = array_pop($traitFolders);

         foreach ($traitFolders as $key => $folder) {
             $file->makeDirectory('app/Http/Traits/' . $folder, 0755, true);

     return $file->put("app/Http/Traits/{$traitName}.php", $newTraitFile);

The above method does create the folders, but not nested. It is creating the folder like this:

|-- Root Trait Folder
    |-- Level-1
    |-- Level-2
    |-- file.php

I know this must be simple to achieve, but I am failing.

Kindly help me out. Thanks.




I will simply change your for loop

$n = 'app/Http/Traits/';
foreach ($traitFolders as $key => $folder) {
         $file->makeDirectory($n. $folder, 0755, true);
         $n .= $folder.'/';