Home / Snippets / How to Copy or Move Files Between 2 Disks in Laravel
How to Copy or Move Files Between 2 Disks in Laravel cover

How to Copy or Move Files Between 2 Disks in Laravel

6.8K

2 years ago

0 comments

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);
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this