Laravel 8 – How to move files from one folder to another folder

In this Laravel tutorial, we will learn how we can move files from one folder to another folder or from one location to another location with a simple example.

When we have to move files from one location to another in our system then it is very is by just copying the file from one location to another and paste it to desired location or folder. The content will move to that particular destination.

But what if we are required to perform the same thing using coding and that too online.

Let’s suppose we have a repository kind of website where users can create the folders and store the content in them. And again if the user wants, he/she can move that folder file to a different folder. So today we will learn how we can perform the same thing with the help of Laravel.

If you are familiar with Linux then there is also a command mv to move the file that needs source and destination. Linux gives us powerful options to take care of all these things easily. But if we have to perform the same thing using coding and then it becomes a little bit tedious. In Laravel, we can achieve it by using move method with File or Storage Facade.

Move file using File Facade

You can use the below line of code to move files from one path to another, you just need to replace the from_path and to_path with their actual path

File::move(from_path, to_path);
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use File;
  
class DemoController extends Controller
{
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    public function moveImage(Request $request)
    {
        File::move(public_path('exist/test.png'), public_path('move/test_move.png'));
   
    
    }
}

Move file using Storage Facade

You can also use Storage Facade to move files:

Storage::move(from_path, to_path);

Let’s suppose you want to move the file ‘file1.jpg’ from the old directory to the new directory then you can use the below line of code

Storage::move('old/file.jpg', 'new/file.jpg');

Example

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Storage;
  
class DemoController extends Controller
{
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    public function moveImage(Request $request)
    {
        Storage::move('exist/test.png', 'move/test_move.png');
   
      
    }
}

Recommended Posts For You

Spread the love