In this article i will help you to copy the folders recursively from one folder to another in laravel .File System is used to perform the file system based operations like copy Folder Recursively. For this purpose laravel uses Illuminate\Filesystem\Filesystem
class in laravel. Laravel provides inbuilt library to access the file system and we can do multiple robust operations using the libraries.
Sometime in our application we want to copy the folder or files from one directory to another in this case we can use File::copyDirectory()
of laravel inbuilt library. If we perform same operations using the core php functions than it can be a hectic or lengthy code to implement but using the packages or library it will be easier to implement.
In this article I will use Illuminate\Filesystem\Filesystem
class and File::copyDirectory()
method to copy the entire directory recursively in the folder.
Method accepts two parameters as belowcopyDirectory
File::copyDirectory($source, $destination)
Example Usage:
File::copyDirectory(public("images"),public("copiedimages"));
Let’s understand copy Folder Recursively from one folder to another in Laravel with example step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project --prefer-dist laravel/laravel blog
You can also read this to start with new project
Step 2 : Create controller
Let’s create a controller and add method performCopyDirectory
php artisan make:controller FolderController
and add the below code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
class FolderController extends Controller
{
public function performCopyDirectory(Request $request){
$sourcePath=public_path('images');
$destinationPath=public_path('copiedimages');
if (!File::exists( $storageDestinationPath)) {
File::copyDirectory($sourcePath,$storageDestinationPath);
}
return response("Folder copied successfully");
}
}
}
In above code First of all we are checking the directory is exist or not then if available then we are copying the directory at the destination location.
Step 3: Create two routes in routes/web.php
Create a route to create the directory
routes/web.php
<?php
use App\Http\Controllers\FolderController;
use Illuminate\Support\Facades\Route;
Route::get("/copy-directory",[FolderController::class,"performcopyDirectory"]);