How can I move a file from one location to another

2019-03-26 23:52发布

问题:

I'm trying to move a file from one place to another place. In this case it is my user profile picture. Since I store my user profile picture base on their username, so when they change their username. I will need to move their profile photo, otherwise, the image link will be broken.

I've tried it here:

if ( $user->username != Input::get('username')) {
    $new_path = public_path().'/img/logo/'. Input::get('username').'/'.$user->logo_path;
    $old_path = public_path().'/img/logo/'. $user->username.'/'.$user->logo_path;
    $move = File::move($new_path, $old_path);
    $delete = File::delete($old_path);
}

I keep getting:

Any suggestions?

回答1:

You're moving the file in the wrong direction.

It should be $move = File::move($old_path, $new_path);

... in other words, the first argument should be the OLD file location, the second argument should be the NEW file location... you have it backwards. :)

From the Laravel Docs

Move A File To A New Location

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

Additionally, as said above, you shouldn't have the File::delete either since that file was moved and therefore deleted.

So, two things:

1) Switch the "old_path" and "new_path" and

2) Remove the File::delete line



回答2:

I suggest you store files based on the user ID instead of username, that way you won't have to move anything when the username changes. Only replace the existing file.