Search code examples
phplaravelfilemove

File move to another folder laravel


I need the last 7 days' storage logs to move a new folder. But, I can't move them and got this error.

rename(/var/www/html/eMarketing/storage/logs/old-log-2020-02-27,/var/www/html/eMarketing/storage/logs/laravel-2020-02-27.log): Not a directory

My Code is here

public function logs() 
{
  $today = \Carbon\Carbon::today()->format('Y-m-d');
  $days  = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');

  $newDirectoryPath = storage_path('logs/old-log-'.$days);
  if (!\File::isDirectory($newDirectoryPath)) {
      \File::makeDirectory($newDirectoryPath);
  }

  $path = storage_path('logs/');
  $allFiles = \File::allFiles($path);

  foreach($allFiles as $files) {
      $file = pathinfo($files);
      $logDay = str_replace('laravel-','', $file['filename']);  

      if ($logDay >= $days && $logDay < $today) {
          \File::move($newDirectoryPath, $path.$file['basename']);
      }

   }
}

Solution

  • Problem

    The problem is, you don't have files to move.

    $newDirectoryPath = storage_path('logs/old-log-' . $days);
    
    if (!\File::isDirectory($newDirectoryPath)) {
        \File::makeDirectory($newDirectoryPath);
    }
    

    The move() method may be used to rename or move an existing file to a new location. But $newDirectoryPath is a folder not a file.


    Solution

    You need to change :

    \File::move(
        $path . $file['basename'],                  // old file
        $newDirectoryPath . '/' . $file['basename'] // new file
    );
    
    public function logs()
    {
        $today = \Carbon\Carbon::today()->format('Y-m-d');
        $days  = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');
    
        $newDirectoryPath = storage_path('logs/old-log-' . $days);
        if (!\File::isDirectory($newDirectoryPath)) {
            \File::makeDirectory($newDirectoryPath);
        }
    
        $path     = storage_path('logs/');
        $allFiles = \File::allFiles($path);
    
        foreach ($allFiles as $files) {
            $file   = pathinfo($files);
            $logDay = str_replace('laravel-', '', $file['filename']);
    
            if ($logDay >= $days && $logDay < $today) {
                \File::move($path . $file['basename'], $newDirectoryPath . '/' . $file['basename']);
            }
    
        }
    }