php - 用户上传新图片时删除文件夹中的上一张图片 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.');
}
解决方案
在用新的更新之前,您需要获取用户的当前图像路径。这样您就可以使用该旧路径删除图像文件。
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.');
}
推荐阅读
- python-2.7 - 如何在 auto-07p 中运行演示代码时修复 RuntimeError 和分段错误
- c# - 如何访问设计 Windows 窗体 C#
- python - 具有不同值的属性的 Django 类
- php - 如何在子查询中使用 Eloquent 模型属性?
- javascript - 将 div 彼此相邻并居中
- excel - VBA - 按最接近的值对列进行排序以回答。最接近的答案将出现在排序列表的顶部
- powershell - PowerShell 方法包含未按预期工作
- r - 是否可以在 R 的匿名函数中命名变量?
- c - GCC 预处理器不工作?有或没有注释的大文件的编译时间
- html - 以百分比计算 getBoundingClientRect