Move command is used to shift the folder or files from one location to another without copy so In this article i will show you move files or folder to one folder to another in Laravel. File System is used to perform the file system based operations like move files and folder. 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 move the folder or files from one directory to another in this case we can use File::move(
or $source,$destination
)Storage::move($source,$destination)
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::
method to move the entire directory recursively in the folder. move(
$source,$destination
)
Method accepts two parameters as belowmove
File::move($source, $destination)
or
Storage::move($source, $destination)
Example Usage:
File::move(public("images"),public("movedimages"));
Let’s understand move Folder or files 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 performMoveFiles
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 performMoveFiles(Request $request){
$sourcePath=public_path('images');
$destinationPath=public_path('movedimages');
if (!File::exists( $storageDestinationPath)) {
File::move($sourcePath,$storageDestinationPath);
}
return response("Folder moved successfully");
}
}
}
In above code First of all we are checking the directory is exist or not then if available then we are moving the directory at the destination location.
Example 2 :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
class FolderController extends Controller
{
public function performMoveFiles(Request $request){
Storage::move("exist/image.jpg","new/profile.jpg");
return response("File moved successfully");
}
}
}
Here we are moving exist/image.jpg
to new location with rename new/profile.jpg
.
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,"performMoveFiles"]);