Posts Learn Components Snippets Categories Tags Tools About
/

How to Copy or Move Files Between 2 Disks in Laravel

Get to know how to copy or move files between 2 disks in Laravel easily by simple code examples

Created on Feb 01, 2022

6363 views

To copy or move files between 2 disks in Laravel you can make use of the "disk()" method to specify the disk. The disk can accept the filesystem configuration such as "public", "s3" or any of your configs.

Using "put" Method to Save the File to the New Disk


For this example, we'll be moving files located from the "public" disk to the "s3" disk.
<?php

Storage::disk('public')->put(
  'new-file-1.jpg',
  Storage::disk('public')->get('old-file-1.jpg')
);

Another Approach To Move File To Different Disk in Laravel


Another approach to move the file to a different disk is to get the directory path for both disks and then use the "File::move()" method to transfer the files. Do refer the code example below for the full code example.
<?php

$sourceFile = '';
$destFile = '';

$sourceDisk = 'public';
$destDisk = 's3';

// convert to full paths
$pathSource = Storage::disk($sourceDisk)->getDriver()->getAdapter()->applyPathPrefix($sourceFile);
$destinationPath = Storage::disk($destDisk)->getDriver()->getAdapter()->applyPathPrefix($destFile);

// make destination folder
if (!File::exists(dirname($destinationPath))) {
    File::makeDirectory(dirname($destinationPath), null, true);
}

File::move($pathSource, $destinationPath);

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)