how to change profile image and delete the old one in laravel

0

I'm learning laravel and I'm doing a user panel where this has an avatar by default, the user can change their profile image, and I can upload the image and deploy it, the problem is that every time I upload a new image, the old one remains in the directory, as I do so that only the image I upload remains in the directory (without deleting the avatar by default)

public function update (Request $ r) {

  if ($r->hasFile('img')) {

    $file = $r->file('img');
    $filename = time().'-'.$file->getClientOriginalName();
    $path = 'avatar';
    $file->move($path, $filename);
    $user_id = Auth::user()->id;
    DB::table('users')->where('id', $user_id)->update(['img' => $filename]);
     }
    Session::flash('success', 'Profile updated.');
    return redirect('profile/'.Auth::user()->name);
}
    
asked by Giovanny Garcia Holguin 13.02.2018 в 19:46
source

1 answer

0

You can do it differently with File

// Delete a single file
File::delete($filename);
// Delete multiple files
File::delete($file1, $file2, $file3);
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);

Or you can with the Storage

use Illuminate\Support\Facades\Storage;

Storage::put('file.jpg', $contents);

Storage::delete('file.jpg');
Storage::delete(['file1.jpg', 'file2.jpg']);

Laravel Storage

    
answered by 13.02.2018 / 21:10
source