laravel - 如何在 Laravel 中取消多个文件的链接

标签 laravel eloquent

我想取消数据库中所有名称为 file name in database 的文件的链接。 我尝试使用这样的代码,但它不起作用:

public function destroy($id)
{
     $infokeg = Infokeg::where('id', $id)->first();
     $image[] = $infokeg->foto_kegiatan
     unlink(public_path("data_file/".json_decode($image)));
     $infokeg->delete();
     return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

最佳答案

File::delete() 将为您处理要删除的文件数组,

首先添加它use Illuminate\Support\Facades\File;

public function destroy($id)
{
 $infokeg = Infokeg::where('id', $id)->first();
 $image[] = $infokeg->foto_kegiatan  
 // pass the array of files to deleted to it. 
 // if $image array is like this $image = ['file1.jpg', 'file2.png'];
 File::delete($image);
 
 return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

方法2

首先添加use Illuminate\Support\Facades\Storage;

public function destroy($id)
{
 $infokeg = Infokeg::where('id', $id)->first();
 $image[] = $infokeg->foto_kegiatan  
 // pass the array of files to deleted to it. 
 // if $image array is like this $image = ['file.jpg', 'file2.jpg'];
 Storage::delete($image);
 
 return redirect('infokeg')->with('msg', 'Data Telah Terhapus');
}

对于方法 2,请参阅 docs


编辑:

将公共(public)路径附加到所有内容,

foreach ($image as &$value) {
   $value = public_path("data_file/".$value);
}

它将公共(public)路径附加到数组中的所有值,然后在 delete() 方法中将其用作参数。

关于laravel - 如何在 Laravel 中取消多个文件的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65090933/

相关文章:

php - 设置 processData : false, contentType : false, 时 CSRF token 不匹配

php - Laravel 变形关系

Laravel 5 通过sendinblue重置密码

.htaccess - 如何构建 Laravel .htaccess 以直接指向公共(public)文件夹并删除 index.php

php - 使用 Laravel Eloquent 处理对话

php - Eloquent/SQL - 获取查询的行号(排名)

php - Laravel: Eloquent 地返回一个我无法迭代的对象

php - Eloquent 观察者没有触发

php - Laravel 启动变量在 Controller 中未定义

eloquent - OctoberCMS 范围不适用