首页 > 解决方案 > 用户上传新图片时删除文件夹中的上一张图片 laravel

问题描述

配置文件控制器.php

---当用户上传新图片时,我想删除文件夹中的前一张图片......我使用 Laravel .....

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    public function index($slug){
        
        return view('profile.index')->with('data', Auth::user()->profile);
    }


    public function uploadPhoto(Request $request) {

$file = $request->file('pic');
$filename = $file->getClientOriginalName();
$path = 'storage/img';

$file->move($path, $filename);
$user_id = Auth::user()->id;

DB::table('users')->where('id',$user_id)->update(['pic' =>$filename]);

return redirect('/editProfile')->withSuccess('Your image was successful.');

}

标签: phplaravelimage

解决方案


在用新的更新之前,您需要获取用户的当前图像路径。这样您就可以使用该旧路径删除图像文件。

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    public function index($slug){

        return view('profile.index')->with('data', Auth::user()->profile);
    }


    public function uploadPhoto(Request $request) {

// Uplaod new image
$file = $request->file('pic');
$filename = $file->getClientOriginalName();
$path = 'storage/img';
$file->move($path, $filename);
$user_id = Auth::user()->id;


// Get current image of user, then delete it
$user = User::find(Auth::user()->id);
File::delete($user->pic);


// Then update profile picture column in database
DB::table('users')->where('id',$user_id)->update(['pic' =>$filename]);

return redirect('/editProfile')->withSuccess('Your image was successful.');

}

推荐阅读