更新Laravel时未删除存储器中的旧文件
我试图在更新新映像时从存储器中删除现有映像。 但每次插入新图像时,都会保留以前的图像 当我将图像从数据库添加到取消链接时,我得到了完整的url i、 e 而只有更新Laravel时未删除存储器中的旧文件,laravel,file,storage,unlink,Laravel,File,Storage,Unlink,我试图在更新新映像时从存储器中删除现有映像。 但每次插入新图像时,都会保留以前的图像 当我将图像从数据库添加到取消链接时,我得到了完整的url i、 e 而只有teacher image/1598097262-85508.jpg 已存储在数据库中 删除图像的功能 public function deleteImageFromStorage($value) { if (!empty($value)) { File::delete('public/' . $value);
teacher image/1598097262-85508.jpg
已存储在数据库中
删除图像的功能
public function deleteImageFromStorage($value)
{
if (!empty($value)) {
File::delete('public/' . $value);
}
}
当更新期间有图像发布时,我在控制器中调用了该方法
更新方法包括
if ($request->hasFile('image')) {
$teacher->deleteImageFromStorage($teacher->image);
$file = $request->file('image');
$filename = time() . '-' . mt_rand(0, 100000) . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('teacher-image', $filename);
$teacher->image = $path;
}
我还使用了Storage::delete()
和unlink
,但它们似乎都不起作用
帮助这就是我在Laravel中删除文件的方式
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class ImagesController extends Controller
{
public function deleteImageFromStorage($value)
{
if ( file_exists( storage_path($value) ) ) {
Storage::delete($value);
}
}
}
确保使用Illumb\Support\Facades\Storage。尝试将deleteImageFromStorage方法更改为:
public function deleteImageFromStorage($value)
{
if (!empty($value)) {
File::delete(public_path($value));
}
}
我必须这样做来解决我的问题。 配置文件下filesystems.php上的配置集正在获取url
public function deleteImageFromStorage($value)
{
$path_explode = explode('/', (parse_url($value))['path']); //breaking the full url
$path_array = [];
array_push($path_array, $path_explode[2], $path_explode[3]); // storing the value of path_explode 2 and 3 in path_array array
$old_image = implode('/', $path_array);
if ($old_image) {
Storage::delete($old_image);
}
}
如果将来有人遇到同样的问题,这可能会有所帮助。您也可以提供更新方法中的代码吗?我已经更新了代码Adrian Sir您是否将图像保存在公用文件夹中?我有公用/teacger图像,然后您已经添加了文件
使用文件代码>位于代码右侧的顶部?是使用Illumb\Support\Facades\File;这一次将其更改为仅文件,不带照明\Support\Facades\不要紧,但不起作用。我不知道为什么我在添加检索到的图像时也会得到。我敢肯定这一定是问题所在。尝试解析url,但没有好主意。尝试添加公共路径($value)是否显示了正确的路径?尝试将其粘贴到浏览器中以查看图像是否可以发布原始存储方法?在我看来,db条目不仅保存了路径,还保存了包括主机名在内的整个链接,如果您移植站点,这将带来问题。您是否检查了存储在数据库中的值?
public function deleteImageFromStorage($value)
{
$path_explode = explode('/', (parse_url($value))['path']); //breaking the full url
$path_array = [];
array_push($path_array, $path_explode[2], $path_explode[3]); // storing the value of path_explode 2 and 3 in path_array array
$old_image = implode('/', $path_array);
if ($old_image) {
Storage::delete($old_image);
}
}