How to move a file to a new location in Laravel?

Question:

How to move a file to a new location from old path in Laravel?

Solution:


First Use Laravel File Facades function Use File at top of the class. Like,
use File;

Then
if(! File::move($file_path, $target_location))
{
    //File Can't move to the target location
}else{
   //File is successfully moved
}

Real Life example of determining if a file is in that folder and then move the file to the new location or in new path.

$file_full_path = public_path().'/images/students/1200.jpg';
$new_location = public_path().'/images/others/';

if(File::exists($file_full_path))
{
    if(! File::move($file_full_path, $new_location ))
    {
       // The File can't move succseefully
    }else
    {
      // File has moved successfully
    }
}


Now see what's in the backend ? Laravel Core function of move() is -
    /**
     * Move a file to a new location.
     *
     * @param  string  $path
     * @param  string  $target
     * @return bool
     */
    public function move($path, $target)
    {
        return rename($path, $target);
    }

So, Laravel move() function use PHP's  rename() function . Rename any path in the target path.


So, we can now easily move any file to a new location in Laravel. That may be a jpg, png, pdf or any kinds of file. It's a pretty one line function.

Note : To get the file path of any file, then use public_path() like the above code, other wise it can't move file to one location to another location in Laravel.


$file_full_path = public_path().'/images/students/1200.jpg';
$new_location = public_path().'/images/others/';


How to move a file to a new location in Laravel?

Tags:
How to move file in Laravel, Move file in Laravel, Move file one path to another directory in Laravel, Change file directory in Laravel, Laravel move an image to another folder, Move something in Laravel.
How to move a file to a new location in Laravel? How to move a file to a new location in Laravel? Reviewed by Maniruzzaman Akash on October 13, 2017 Rating: 5

No comments:

Powered by Blogger.