[英]I am trying to download multiple image as a zip file but getting error using laravel 7
I am trying to download multiple images as a zip file but getting errors Invalid argument supplied for foreach() please help me how i resolve that thanks.我正在尝试将多个图像下载为 zip 文件,但出现错误foreach() 提供的参数无效,请帮助我如何解决该问题,谢谢。
Check the error: https://flareapp.io/share/47qG2A3m检查错误: https : //flareapp.io/share/47qG2A3m
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}
You are returning a string, you can't handle it like an array.你正在返回一个字符串,你不能像数组一样处理它。
It's JSON, you can just use :它是 JSON,你可以使用:
$inboxFiles = json_decode(Inbox::where('id', $id)->first()->file);
(the above code is not really robust, but you have the way) (上面的代码不是很健壮,但你有办法)
I know this has already been answered, but do not use json_decode
any more in Laravel...我知道这已经回答了,但不要使用json_decode
在Laravel更多...
Cast the field file
as a JSON
/ array
, so it will automatically be an array and when you save it in the database, it will be transformed to JSON, and when you want to read it back, it will be automatically transformed to array... 铸造领域的file
作为JSON
/ array
,所以它会自动将一个数组,当你将它保存在数据库中,它会转化为JSON,当你想读回,它会自动转换为数组。 ..
To do so, you have to edit Inbox
model and add this property:为此,您必须编辑Inbox
模型并添加此属性:
protected $casts = ['file' => 'array'];
And that's it, then you have to use the field as if it is already an array, so leaving your code as it is in your question, without any edit, it will work right away:就是这样,然后您必须像使用该字段一样使用该字段,就好像它已经是一个数组一样,因此将您的代码保留在您的问题中,无需任何编辑,它将立即起作用:
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.